我编写了一个程序,它创建了一个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条件下都使用它?
答案 0 :(得分:0)
由于你有一些代码重复,我只需要使用类似的东西:
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();
}
另外,要非常小心显示器的行为。 (线程等待/通知队列)。