public class ThreadTest3
{
public static void main(String[] args)
{
MyThread3 myThread3 = new MyThread3();
Thread t1 = new Thread(myThread3);
Thread t2 = new Thread(myThread3);
t1.setName("线程1");
t2.setName("线程2");
t1.start();
t2.start();
}
}
class MyThread3 implements Runnable
{
private int result = 1; // 共享数据
@Override
public void run()
{
while (true){ // 循环打印
synchronized (this)
{
notify(); // 唤醒被wait();方法阻塞的线程
if (result <= 100)
{
System.out.println(Thread.currentThread().getName() + ":打印:" + result);
result++;
}
else
{
break; // 退出当前循环
}
try
{
wait(); // 使用wait();方法第一个线程进入打印完一次之后就进入阻塞状态
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
补充说明:
notify(): 旦执行此方法,就会唤醒被wait的一个线程。 如果有多个线程被wait,就唤醒优先級高的
notifyAll():一旦执行此方法,就会唤醒所有被wait的线程
wait(), notify(), notifyAll()三个方法必须使用在同步代码块或同步方法中。
wait(), notify(), notifyAll()三个方法的调用者必须是同步代码块或同步方法中的同步监视器否则,会出现java.lang.IllegalMonitorStateException异常
wait(), notify(), notifyAll()三个方法是定义在java.long.0bject类中。