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 楼答案
因为这里有一些代码重复,我只想说:
另外,要注意班长的行为。(线程等待/通知队列)