java共享缓冲区的例子,必须实现读写的同步,分别用了4个不同的JAVA代码来演示此功能,先来看主文件:Buffer.java代码:
01 | package thread; |
02 | // 生产者与消费者共享的缓冲区,必须实现读、写的同步 |
03 | public class Buffer { |
04 | PRivate int contents; |
05 | private boolean available = false ; |
06 | public synchronized int get() { |
07 | while (! available) { |
08 | try { |
09 | this .wait(); |
10 | } catch (InterruptedException exc) {} |
11 | } |
12 | int value = contents; |
13 | // 消费者取出内容,改变存取控制available |
14 | available = false ; |
15 | System.out.println( "取出" + contents); |
16 | this .notifyAll(); |
17 | return value; |
18 | } |
19 | public synchronized void put( int value) { |
20 | while (available) { |
21 | try { |
22 | this .wait(); |
23 | } catch (InterruptedException exc) {} |
24 | } |
25 | contents = value; |
26 | available = true ; |
27 | System.out.println( "放入" + contents); |
28 | this .notifyAll(); |
29 | } |
30 | } |
Consumer.java,消费者进程:
01 | package thread; |
02 | // 消费者线程 |
03 | public class Consumer extends Thread { |
04 | private Buffer buffer; |
05 | private int number; |
06 | public Consumer(Buffer buffer, int number) { |
07 | this .buffer = buffer; |
08 | this .number = number; |
09 | } |
10 | public void run() { |
11 | for (;;) { |
12 | int v = buffer.get(); |
13 | System.out.println( "消费者#" + number + "消费" + v); |
14 | } |
15 | } |
16 | } |
Producer.java 生产者线程:
01 | package thread; |
02 | // 生产者线程 |
03 | public class Producer extends Thread { |
04 | private Buffer buffer; |
05 | private int number; |
06 | public Producer(Buffer buffer, int number) { |
07 | this .buffer = buffer; |
08 | this .number = number; |
09 | } |
10 | public void run() { |
11 | for ( int i = 0 ;;) { |
12 | buffer.put(i); |
13 | System.out.println( "生产者#" + number + "生产 " + i++); |
14 | try { |
15 | Thread.sleep(( int ) (Math.random() * 100 )); |
16 | } catch (InterruptedException exc) {} |
17 | } |
18 | } |
19 | } |
ProducerConsumerProblem.java:演示生产者∕消费者问题
view sourceprint?01 | package thread; |
02 | // 演示生产者∕消费者问题的主程序 |
03 | public class ProducerConsumerProblem { |
04 | public static void main(String[] args) { |
05 | Buffer buffer = new Buffer(); |
06 | new Producer(buffer, 100 ).start(); |
07 | new Consumer(buffer, 300 ).start(); |
08 | new Consumer(buffer, 301 ).start(); |
09 | } |
10 | } |
新闻热点
疑难解答