有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java 2线程交替打印数字的正确方法

我写了一个程序,它创建了一个2个新线程,并共享一个公共锁对象来交替打印数字。 想知道使用wait()和notify()的方法是否正确吗

主课

public class MyMain {
public static void main(String[] args) {
MyThread1 obj = new MyThread1();

    Thread thread1 = new Thread(obj);
    Thread thread2 = new Thread(obj);

    thread1.setName("t1");
    thread2.setName("t2");

    thread1.start();
    thread2.start();
}
}

线程类

public class MyThread1 implements Runnable{
    int i = 0;
    @Override
    public synchronized void run() {
        while(i<10)
        {
            if(i%2==0)
            {   
                try{
                    notify();
                    System.out.println(Thread.currentThread().getName()+" prints "+i);
                    i++;
                    wait();

                 }catch(Exception e){ e.printStackTrace(); }
            }else
            {
                try{
                    notify();
                    System.out.println(Thread.currentThread().getName()+" prints "+i);
                    i++;
                    wait();
                }catch(Exception e){ e.printStackTrace(); }
            }
        }
    }
}

wait()和notify()是否可以更好地使用,而不是在两种if条件下都使用它


共 (1) 个答案

  1. # 1 楼答案

    因为这里有一些代码重复,我只想说:

    while(true) {
        //If it's not my turn I'll wait.
        if(i%2==0) wait();
    
        // If I've reached this point is because: 
        // 1 it was my turn OR 2 someone waked me up (because it's my turn)
        System.out.println(Thread.currentThread()": "+i);
        i++; // Now is the other thread's turn
        // So we wake him up
        notify();
    }
    

    另外,要注意班长的行为。(线程等待/通知队列)