结婚后

class Producer implements Runnable {//生产者
2. Queue queue;
3. public Producer(Queue q){
4. queue = q;
5. }
6. @Override
7. public void run() {
8. for(int i=0;i<10;i++){
9. queue.put(i);
10. System.out.println("producter: "+i);
11. }
12. }
13. }
14. class Consumer implements Runnable {//消费者
15. Queue queue;
16. public Consumer(Queue q) {
17. queue = q;
18. }
19. @Override
20. public void run() {
21. for(int i = 0; i < 10; i++){
22. System.out.println("Consumer: "+queue.get());
23. }
24. }
25.
26. }
27.
28. class Queue {// 缓冲区,这里以队列来表示
29. int value;
30. boolean bFull = false;
31. public synchronized void put(int i){
32. if(!bFull){
33. value = i;
34. bFull = true;
35. notify();
36. }
37. try {
38. wait();
39. } catch (Exception e) {
40. e.printStackTrace();
41. }
42. }
43. public synchronized int get(){
44. if(!bFull){
45. try {
46. wait();
47. } catch (Exception e) {
48. e.printStackTrace();
49. }
50. }
51. bFull = false;
52. notify();
53. return value;
54.
55. }
56.
57. }
58. public class Test {//测试类
59. public static void main(String[] args){
60. Queue queue = new Queue();
61. Producer producer = new Producer(queue);
62. Consumer consumer = new Consumer(queue);
63. Thread t1 = new Thread(producer);
64. Thread t2 = new Thread(consumer);
65. t1.start();
66. t2.start();
67. }
68. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值