Object类的方法:等待wait() , 唤醒队首线程notify() , 唤醒全部等待线程notifyAll()。利用等待和唤醒实现Producer线程、Consumer线程的互斥访问Message对象。
代码如下:
package ThreadDemo; class Message { private String msg = ""; private boolean flag = true; //记录型信号量,规定true表示没有消息(允许生产、不许消费),false表示已有消息(不许生产、允许消费) public synchronized void setMessage(String msg) { if(flag==false) { try { super.wait(); //不许生产、让Producer线程等待 } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } this.msg=msg; flag = false; //生产完成,改变信号量、唤醒Consumer super.notify(); } public synchronized String getMessage() { if(flag==true) { try { super.wait(); //不许消费、让Consumer线程等待 } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } try { return "msg = "+this.msg; } finally { //return后用finally确保指令执行 flag = true; //消费完成,改变信号量、唤醒Producer super.notify(); } } } class Producer implements Runnable{ private Message msg; public Producer(Message msg) { this.msg = msg; } @Override public void run() { for(int x=0;x<30;x++) { if(x%2==0) { msg.setMessage("夏天,穿短袖短裤"); } else { msg.setMessage("冬天,换秋衣秋裤"); } } } } class Consumer implements Runnable{ private Message msg; public Consumer(Message msg) { this.msg = msg; } @Override public void run() { for(int x=0;x<30;x++) { System.out.println(msg.getMessage()); } } } public class Main { public static void main(String[] args){ Message msg = new Message(); new Thread(new Producer(msg)).start(); //启动生产者线程 new Thread(new Consumer(msg)).start(); //启动消费者线程 } }