今天写了一个java线程通讯的例子,两段代码只是有无else的问题,但执行效果却不同,想不明白为什么,还请高手赐教
代码1:
class="java">//资源 class Resource { private String name; private String sex; private boolean flag;//true:已赋值完成,应该输出;false:已输出需要新赋值 public synchronized void set(String name, String sex) { if(this.flag) { try { this.wait(); } catch(InterruptedException e) {} } //else { this.name = name; this.sex = sex; this.flag = true; this.notify(); //} } public synchronized void out() { if(!this.flag) { try { this.wait(); } catch(InterruptedException e) {} } //else { System.out.println(this.name + ",性别 :" + this.sex); this.flag = false; this.notify(); //} } } //任务1 - 给资源赋值 class Task1Input implements Runnable { Resource resource; public Task1Input(Resource resource) { this.resource = resource; } public void run() { int syscle = 0; while(true) { if(syscle == 0) { resource.set("Jack", "man"); } else { resource.set("露丝", "女"); } syscle = (syscle+1)%2; } } } //任务2 - 输出资源 class Task2Output implements Runnable { Resource resource; public Task2Output(Resource resource) { this.resource = resource; } public void run() { while(true) { resource.out(); } } } class ThreadCommunication { public static void main(String[] args) { //统一的资源 Resource resource = new Resource(); //不同的任务 Task1Input task1 = new Task1Input(resource); Task2Output task2 = new Task2Output(resource); Thread thread1 = new Thread(task1); Thread thread2 = new Thread(task2); thread1.start(); thread2.start(); } }
?执行结果是 “Jack,性别 :man” 和 “露丝,性别 :女” ?交替循环打印。
?
代码2:
//资源 class Resource { private String name; private String sex; private boolean flag;//true:已赋值完成,应该输出;false:已输出需要新赋值 public synchronized void set(String name, String sex) { if(this.flag) { try { this.wait(); } catch(InterruptedException e) {} } else { this.name = name; this.sex = sex; this.flag = true; this.notify(); } } public synchronized void out() { if(!this.flag) { try { this.wait(); } catch(InterruptedException e) {} } else { System.out.println(this.name + ",性别 :" + this.sex); this.flag = false; this.notify(); } } } //任务1 - 给资源赋值 class Task1Input implements Runnable { Resource resource; public Task1Input(Resource resource) { this.resource = resource; } public void run() { int syscle = 0; while(true) { if(syscle == 0) { resource.set("Jack", "man"); } else { resource.set("露丝", "女"); } syscle = (syscle+1)%2; } } } //任务2 - 输出资源 class Task2Output implements Runnable { Resource resource; public Task2Output(Resource resource) { this.resource = resource; } public void run() { while(true) { resource.out(); } } } class ThreadCommunication { public static void main(String[] args) { //统一的资源 Resource resource = new Resource(); //不同的任务 Task1Input task1 = new Task1Input(resource); Task2Output task2 = new Task2Output(resource); Thread thread1 = new Thread(task1); Thread thread2 = new Thread(task2); thread1.start(); thread2.start(); } }
?执行结果却不是交替打印,不知什么原因,请赐教。
?