多线程wait和notify实现1212
package threadT; public class ThreadMain { public static void main(String args[]) { final Object obj = new Object();// 以该对象为共享资源 new Thread(new Thread1to2(1, obj), "小明").start(); new Thread(new Thread1to2(2, obj), "小王").start(); } }
package threadT; public class Thread1to2 implements Runnable { private final int number; private int count = 10; public Object obj; public Thread1to2(int number, Object obj) { this.obj = obj; this.number = number; } public void run() { synchronized (obj) { while (count-- > 0) { try { obj.notify();// 唤醒等待res资源的线程,把锁交给线程(该同步锁执行完毕自动释放锁) System.out.println(Thread.currentThread().getName() + "喊:" + number); if (count > 0) obj.wait();// 释放CPU控制权,释放res的锁,本线程阻塞,等待被唤醒。 // 如果结束要释放锁,否则会阻塞进程 else if (count == 0) obj.notify(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }