题目内容
分析程序,写出结果class Info{private String name="张三";private boolean flag=false;public synchronized void set(String name){if(!flag){try {super.wait();} catch (InterruptedException e) {e.printStackTrace();}}this.setName(name);try {Thread.sleep(300);} catch (InterruptedException e) {e.printStackTrace();}flag=false;super.notify();}public synchronized void get(){if(flag){try {super.wait();} catch (InterruptedException e) {e.printStackTrace();}}try {Thread.sleep(300);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(this.getName()+"-->" );flag=true;super.notify();}public String getName() {return name;}public void setName(String name) {this.name = name;}}class Producer implements Runnable{private Info info=null;public Producer(Info info){this.info=info;}@Overridepublic void run() {boolean flag=false;for(int i=0;i<20;i++){if(flag){this.info.set("张三");flag=false;}else{this.info.set("李四");flag=true;}}}}class Consumer implements Runnable{private Info info=null;public Consumer(Info info){this.info=info;}@Overridepublic void run() {for(int i=0;i<20;i++){try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}this.info.get();}}}public class ThreadDemo2 {public static void main(String[] args) {Info i=new Info();Producer pro=new Producer(i);Consumer con=new Consumer(i);new Thread(pro).start();new Thread(con).start();}}
查看答案
搜索结果不匹配?点我反馈