1101354051 1101354051
关注数: 8 粉丝数: 18 发帖数: 839 关注贴吧数: 12
求大神解决,这个程序是怎么运行的,新手初学请指教 package com.jiangwei2; class Info { // 定义信息类 private String name = "华新李"; // 信息名称,指定默认值 private String content = "JAVA讲师"; // 信息内容,指定默认值 private boolean flag=false; public String getName() { // 取得信息名称 return name; // 返回信息名称 } public void setName(String name) { // 设置信息名称 this.name = name; // 设置name属性内容 } public String getContent() { // 取得信息内容 return content; // 返回信息内容 } public void setContent(String content) { // 设置信息内容 this.content = content; // 设置content属性内容 } public synchronized void set(String name,String content) { if(!flag) { try { super.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.setName(name); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } this.setContent(content); flag=false; super.notify(); } public synchronized void get() { try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(this.getName()+" 是 "+this.getContent()); flag=true; super.notifyAll(); } } class Producer implements Runnable { // 定义生产者线程private Info info = null; // 保存Info引用 public Producer(Info info) { // 通过构造方法设置Info属性内容 this.info = info; // 为info属性初始化 } public void run() { // 覆写run()方法 boolean flag = false; // 定义标记位 for (int i = 0; i < 5; i++) { if(flag==true) { this.info.set("李兴华", "JAVA讲师"); flag=false; }else { this.info.set("ht k", "http://tieba.baidu.com/mo/q/checkurl?url=http%3A%2F%2Fwww.mldnjava.cn&urlrefer=888f7acf33e8b56f09b37b02d17c4298"); flag=true; } } } } class Consumer implements Runnable { // 定义消费者线程 private Info info = null; // 保存Info引用 public Consumer(Info info) { // 通过构造方法设置Info属性内容 this.info = info; // 为info属性初始化 } public void run() { // 覆写run()方法 for (int i = 0; i < 5; i++) { // 循环50次 try { Thread.sleep(10);// 加入延迟 } catch (InterruptedException e) { e.printStackTrace(); } this.info.get(); } } } public class ThreadCaseDemo01 { public static void main(String[] args) { Info i = new Info(); // 实例化Info对象 Producer pro = new Producer(i); // 实例化生产者,传递Info引用 Consumer con = new Consumer(i); // 实例化消费者,传递Info引用 new Thread(pro).start(); // 启动生产者线程 new Thread(con).start(); // 启动消费者线程 } }
1 下一页