代码(等待程序)1.
- package waitnotify2;
- public class MyThread implements Runnable{
- Object o ;
- public MyThread(Object o){
- this.o = o;
- }
- public void run() {
- synchronized(o){
- System.out.println("等待中...");
- try {
- o.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("等待结束");
- }
- }
- }
代码2(唤醒程序):
- package waitnotify2;
- public class NotifyAll implements Runnable{
- Object o ;
- public NotifyAll(Object o){
- this.o = o;
- }
- public void run() {
- synchronized(o){
- System.out.println("唤醒之前");
- try {
- Thread.sleep(7000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- o.notifyAll();
- System.out.println("唤醒了,哈哈");
- }
- }
- }
至此,我们就可以对上面的代码进行测试了:
- package waitnotify2;
- public class MainThread {
- public static void main(String[] args) {
- Object o = new Object();//生成一个Object型对象
- MyThread myThread = new MyThread(o);//在此处体现了对同一对象的操作
- Thread t1 = new Thread(myThread);
- Thread t2 = new Thread(myThread);
- Thread t3 = new Thread(myThread);
- Thread t4 = new Thread(myThread);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- NotifyAll na = new NotifyAll(o);//在此处体现了对同一对象的操作
- Thread t = new Thread(na);
- t.start();
- }
- }
好看一下运行结果:
----------------------------------------------------------------------------------------
等待中...等待中...
等待中...
等待中...
唤醒之前 (注意,在此行之前的代码最先被打印,也即是所有的线程将被处于休眠状态,等待唤醒代码执行后,下面的语句即被打印)
唤醒了,哈哈
等待结束
等待结束
等待结束
等待结束
----------------------------------------------------------------------------------------