BBS水木清华站∶精华区

发信人: muslov (刚刚好), 信区: Java        
标  题: Re: 请教线程的同步与互斥 
发信站: BBS 水木清华站 (Thu Jan 11 13:52:07 2001) 
 
经典的(多)生产者,(多)消费者问题,是没有考虑堆栈上溢的。 
你把数据结构改成队列吧。 
3 public class SyncTest { 

5 public static void main(String[] args) { 

7 SyncStack stack = new SyncStack(); 

9 Producer p1 = new Producer(stack); 
10 Thread prodT1 = new Thread (p1); 
11 prodT1.start(); 
12 
13 Producer p2 = new Producer(stack); 
14 Thread prodT2 = new Thread (p2); 
15 prodT2.start(); 
16 
17 Consumer c1 = new Consumer(stack); 
18 Thread consT1 = new Thread (c1); 
19 consT1.start(); 
20 
21 Consumer c2 = new Consumer(stack); 
22 Thread consT2 = new Thread (c2); 
23 consT2.start(); 
24 } 
25 } 
3 public class Producer implements Runnable { 
4 private SyncStack theStack; 
5 private int num; 
6 private static int counter = 1; 

8 public Producer (SyncStack s) { 
9 theStack = s; 
10 num = counter++; 
11 } 
12 
13 public void run() { 
14 char c; 
15 for (int i = 0; i < 200; i++) { 
16 c = (char)(Math.random() * 26 +'A'); 
17 theStack.push(c); 
18 System.out.println("Producer" +num+ ": " +c); 
19 try { 
20 Thread.sleep((int)(Math.random() * 300)); 
21 } catch (InterruptedException e) { 
22 // ignore it 
23 } 
24 } 
25 } 
26 } 
public class Consumer implements Runnable { 
4 private SyncStack theStack; 
5 private int num; 
6 private static int counter = 1; 

8 public Consumer (SyncStack s) { 
9 theStack = s; 
10 num = counter++; 
11 } 
12 
13 public void run() { 
14 char c; 
15 for (int i = 0; i < 200; i++) { 
16 c = theStack.pop(); 
17 System.out.println("Consumer"+num+": " +c); 
18 
19 try { 
20 Thread.sleep((int)(Math.random() * 300)); 
21 } catch (InterruptedException e) { } 
22 
23 } 
24 } 
25 } 
  import java.util.*; 

5 public class SyncStack { 
6 private List buffer = new ArrayList(400); 

8 public synchronized char pop() { 
9 char c; 
10 while (buffer.size() == 0) { 
11 try { 
12 this.wait(); 
13 } catch (InterruptedException e) { 
14 // ignore it... 
15 } 
16 } 
17 c = ((Character)buffer.remove(buffer.size()-1)). 
18 charValue(); 
19 return c; 
20 } 
21 
22 public synchronized void push(char c) { 
23 this.notify(); 
24 Character charObj = new Character(c); 
25 buffer.addElement(charObj); 
26 } 
27 } 
 
-- 
 
※ 修改:·muslov 於 Jan 11 13:52:54 修改本文·[FROM:   166.111.68.91] 
※ 来源:·BBS 水木清华站 smth.org·[FROM: 166.111.68.91] 

BBS水木清华站∶精华区