Java Synchronized与wait notify 连用-2 简化版

来源:互联网 发布:ansys15.0软件 编辑:程序博客网 时间:2024/06/06 15:43
class Resource{String name;String sex;boolean flag = false;public synchronized void  set(String name, String sex){if(this.flag){try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}this.name = name;this.sex = sex;this.flag = true;this.notify();}public synchronized void out(){if(!this.flag){try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}System.out.println(this.name + "..." + this.sex);this.flag = false;this.notify();}}class Input implements Runnable{Resource resource = new Resource();public Input(Resource resource){this.resource = resource;}public void run(){boolean flag = true;while(true){this.resource.getClass();if(flag){resource.set("mike", "man");flag = false;}else{resource.set("lili", "femal");flag = true;}}//while}}class Output implements Runnable{Resource resource = new Resource();public Output(Resource resource) {// TODO Auto-generated constructor stubthis.resource = resource;}@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){resource.out();}}}public class HeiMa {public static void main(String[] args){Resource resource = new Resource();Thread t1 = new Thread(new Input(resource));Thread t2 = new Thread(new Output(resource));t1.start();t2.start();}}

0 0