使用 2 个线程打印偶数和奇数

您好,我正在尝试使用名为 EvenThread 和 OddThread 的两个线程打印偶数和奇数,有时我得到正确的结果,有时却没有,有人可以帮助我吗?


package com.java8;


public class EvenOddExample {


    public static synchronized void print(int i,String name){

            System.out.println(i+"--->"+name);

    }

    public static void main(String[] args) throws InterruptedException {

        EvenThread e=   new EvenThread();

        e.start();

        OddThread o=new OddThread();

        o.start();


    }

    public static class EvenThread extends Thread{


        public void run() {

            for(int i=0;i<10;i++){

                if(i%2==0){

                    print(i,"Even");

                }else{

                    try {

                        Thread.sleep(1000);

                    } catch (InterruptedException e) {

                        // TODO Auto-generated catch block

                        e.printStackTrace();

                    }

                }

            }


        }


    }


    public static class OddThread extends Thread{


        @Override

        public void run() {

            for(int i=1;i<10;i++){

                if(i%2!=0){

                    print(i,"Odd");

                }else{

                    try {

                        Thread.sleep(1000);

                    } catch (InterruptedException e) {

                        // TODO Auto-generated catch block

                        e.printStackTrace();

                    }

                }

            }


        }


    }

}


蛊毒传说
浏览 137回答 3
3回答

四季花海

您需要两个线程之间的一些信号。放置synchronized方法print只是保证一次只有一个线程可以进入该方法。可以使用您的线程Object.wait()和方法。Object.notify{All}()实际上这是某种Sender-Receiver Synchronization Problem。我调整了您的代码。另外我使用了ExecutorServiceandCallable而不是 extending Thread,这是不好的做法:import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class EvenOddExample {  private static boolean evensTurn = true;  private static Object monitor = new Object();  public static void print(int i, String name) {    System.out.println(i + "--->" + name);  }  public static void main(String[] args) throws InterruptedException {    final ExecutorService executorService = Executors.newFixedThreadPool(2);    executorService.submit(new EvenCallable());    executorService.submit(new OddCallable());    executorService.shutdown();  }  public static class EvenCallable implements Callable<Void> {    @Override    public Void call() throws InterruptedException {      for (int i = 0; i < 10; i++) {        if (i % 2 == 0) {          synchronized (monitor) {            while (!evensTurn) { // not your turn?              monitor.wait(); // wait for monitor in a loop to handle spurious wakeups            }            print(i, "Even");            evensTurn = false; // next odd needs to run            monitor.notifyAll(); // wakeup the odd thread          }        } else {          Thread.sleep(1000);        }      }      return null;    }  }  public static class OddCallable implements Callable<Void> {    @Override    public Void call() throws InterruptedException {      for (int i = 1; i < 10; i++) {        if (i % 2 != 0) {          synchronized (monitor) {            while (evensTurn) {              monitor.wait();            }            print(i, "Odd");            evensTurn = true;            monitor.notifyAll();          }        } else {          Thread.sleep(1000);        }      }      return null;    }  }}

慕斯王

synchronized 用于锁定另一个线程的访问,当被锁定的对象空闲时,它不保证下一个调用哪个线程。您可以使用信号量进行线程间通信:&nbsp; private static Semaphore[] semaphores = {new Semaphore(0), new Semaphore(1)};&nbsp; static void print(int i, String name) {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; semaphores[(i + 1) % 2].acquire();&nbsp; &nbsp; } catch (InterruptedException e) {&nbsp; &nbsp; &nbsp; Thread.currentThread().interrupt();&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(i + "--->" + name);&nbsp; &nbsp; semaphores[i % 2].release();&nbsp; }

holdtom

public class EvenOddPrinter {&nbsp; &nbsp; static boolean flag = true;&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; class Odd implements Runnable {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 1; i <= 10;) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (EvenOddPrinter.flag) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(i + "--->odd");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i += 2;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; EvenOddPrinter.flag = !EvenOddPrinter.flag;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; class Even implements Runnable {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 2; i <= 10;) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!EvenOddPrinter.flag) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(i + "---->even");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i += 2;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; EvenOddPrinter.flag = !EvenOddPrinter.flag;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; Runnable odd = new Even();&nbsp; &nbsp; &nbsp; &nbsp; Runnable even = new Odd();&nbsp; &nbsp; &nbsp; &nbsp; Thread t1 = new Thread(odd, "Odd");&nbsp; &nbsp; &nbsp; &nbsp; Thread t2 = new Thread(even, "Even");&nbsp; &nbsp; &nbsp; &nbsp; t1.start();&nbsp; &nbsp; &nbsp; &nbsp; t2.start();&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java