读书人

一天一代码 :Java线程基础通信

发布时间: 2012-09-22 21:54:54 作者: rapoo

一天一代码 :Java线程基础通讯
01 /*
02 java1.4??? 线程通信
03 */
04
05
06 class Resource
07 {
08 ??? private String name;
09 ??? private int count = 1;
10 ??? private boolean flag = false;
11 ???
12 ??? public synchronized void set(String name)
13 ??? {
14 ??????? while(flag)
15 ??????????? try
16 ??????????? {
17 ??????????????? this.wait();
18
19 ??????????? }
20 ??????????? catch (Exception e)
21 ??????????? {
22 ??????????? }
23 ??????????? this.name=name+count++;
24 ??????????? System.out.println(Thread.currentThread().getName()+"...生产者.."+ this.name);
25 ??????????? flag=true;
26 ??????????? notifyAll();
27 ???????
28 ??? }
29
30 ??? public synchronized void out()
31 ??? {
32 ??????? while(!flag)
33 ??????? try
34 ??????? {
35 ??????????? this.wait();
36 ??????? }
37 ??????? catch (Exception e)
38 ??????? {
39 ??????? }
40 ??????? System.out.println(Thread.currentThread().getName()+this.name);
41 ??????? flag=false;
42 ??????? notifyAll();
43 ??? }
44 }
45 class Produce implements Runnable
46 {
47 ??? Resource res;
48 ??? Produce(Resource res)
49 ??? {
50 ??????? this.res = res ;
51 ??? }
52 ??? public void run()
53 ??? {
54 ??????? while(true)
55 ??????????? res.set("商品");
56 ??? }
57 }
58
59 class Consumer implements Runnable
60 {
61 ??? Resource res;
62
63 ??? Consumer(Resource res)
64 ??? {
65 ??????? this.res = res ;
66 ??? }
67
68 ??? public void run()
69 ??? {
70 ??????? while(true)
71 ??????????? res.out();
72 ??? }
73 }
74
75 class ProConsumer
76 {
77 ??? public static void main (String[] args)
78 ??? {
79 ??????? Resource r = new Resource();
80 ??????? Produce? pro = new Produce(r);
81 ??????? Consumer con = new Consumer(r);
82
83 ??????? Thread t1 = new Thread(pro);
84 ??????? Thread t2 = new Thread(pro);
85 ??????? Thread t3 = new Thread(con);
86 ??????? Thread t4 = new Thread(con);
87
88 ??????? t1.start();
89 ??????? t2.start();
90 ??????? t3.start();
91 ??????? t4.start();
92
93 ??? }
94 }
[/font]

读书人网 >编程

热点推荐