一、使用wait和notify方法

package wait.notify;import java.util.ArrayList;import java.util.List;/*使用wait方法和notify方法实现“生产者消费者模式” */public class ThreadTest16 { public static void main(String[] args) { List list = new ArrayList(); Thread t1 = new Thread(new Producer(list)); Thread t2 = new Thread(new Consumer(list)); t1.setName("生产者线程"); t2.setName("消费者线程"); t1.start(); t2.start(); }}//生产线程class Producer implements Runnable{ //仓库 private List list; public Producer(List list) { this.list = list; } @Override public void run() { //一直生产 while (true){ synchronized (list){ if (list.size() >0){ //等待 try { list.wait();//当前线程进入等待状态,并且释放锁 } catch (InterruptedException e) { e.printStackTrace(); } } //仓库空,可以生产 Object obj = new Object(); list.add(obj); System.out.println(Thread.currentThread().getName()+"--->"+obj); list.notifyAll(); } } }}//消费线程class Consumer implements Runnable{ private List list; public Consumer(List list) { this.list = list; } @Override public void run() { //一直消费 while (true){ synchronized (list){ if (list.size() == 0){ try { list.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //仓库中有数据,可进行消费 Object obj = list.remove(0); System.out.println(Thread.currentThread().getName()+"--->"+obj); //唤醒生产者生产 list.notifyAll(); } } }}
2.实现奇偶输出
package wait.notify;public class jiou { public static void main(String[] args) { Num num = new Num(1); Thread t1 = new Thread(new ji(num)); Thread t2 = new Thread(new ou(num)); t1.setName("t1"); t2.setName("t2"); t1.start(); t2.start(); }}class Num{ int i; public Num(int i) { this.i = i; }}class ji implements Runnable{ private Num num; public ji(Num num) { this.num = num; } @Override public void run() { for (int j=0;j<10;j++){ synchronized (num){ if (num.i%2 == 0){ try { num.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+"--->"+(num.i)); num.i++; num.notifyAll(); } } }}class ou implements Runnable{ private Num num; public ou(Num num) { this.num = num; } @Override public void run() { for (int j = 0 ;j<10;j++){ synchronized (num){ if (num.i%2 !=0){ try { num.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+"--->"+(num.i)++); num.notifyAll(); } } }}