java 线程(七)等待与唤醒
package cn.sasa.demo5; public class Resources { private String name; private boolean gender; //标记 public boolean flag; //如果falg==true ,赋值完成 //如果flag==false 取值完成 public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isGender() { return gender; } public void setGender(boolean gender) { this.gender = gender; } private Resources() {} public static final Resources resource = new Resources(); }
package cn.sasa.demo5; public class InputRunnable implements Runnable{ private Resources rs = Resources.resource; @Override public void run() { int flag = 1000; while(flag > 0) { synchronized(rs) { //input 和 output 两个线程操作同一个数据源,必须保证同步锁是同一个锁 if(rs.flag) { try { rs.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(flag % 2 ==0) { rs.setName("来福"); rs.setGender(true); }else { rs.setName("wangcai"); rs.setGender(false); } rs.flag=true; rs.notify(); flag--; } } } /** * 等待 唤醒机制 * * input先拿到cup的执行资源,wait(),等待output输出 * * output输出后,notify()唤醒input,自己再wait() * * input被唤醒后继续执行,执行完后,notify() output线程,自己再wait() */ }
package cn.sasa.demo5; public class OutputRunnable implements Runnable{ private Resources rs = Resources.resource; @Override public void run() { int flag = 1000; while(flag > 0) { synchronized(rs) { //input 和 output 两个线程操作同一个数据源,必须保证同步锁是同一个锁 if(!rs.flag) { try { rs.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(rs.getName() + "======" + rs.isGender() ); rs.flag=false; rs.notify(); flag--; } } } }
package cn.sasa.demo5; public class Test { public static void main(String[] args) { Runnable input = new InputRunnable(); Runnable output = new OutputRunnable(); new Thread(input).start(); new Thread(output).start(); } }