JAVA多线程编程:wait() 和 notify() 方法示例

一个简单的生产者和消费者的之间的产品流通示例,利用java多线程编程,产生生产者和消费者两个子线程访问同步方法。演示了wait()和notify()方法的基本含义 ^_^ 代码如下:

JAVA多线程编程:wait() 和 notify() 方法示例

下载: Counter.java
  1. class Counter {
  2. int n;
  3. boolean valueSet = false ;
  4. synchronized int get() {
  5. if (!valueSet)
  6. try{
  7. wait();
  8. }catch(InterruptedException e){
  9. System.out.println("InterruptedExcepitons Caught in Get Methord");
  10. }
  11.  
  12. System.out.println("Got: "+n);
  13. valueSet = false ;
  14. notify();
  15. return n;
  16. }

 

  1. synchronized void put(int n){
  2. if(valueSet)
  3. try{
  4. wait();
  5. }catch(InterruptedException e){
  6. System.out.println("InterruptedException Caught in Put Methord");
  7.  
  8. }
  9. this.n = n;
  10. valueSet = true ;
  11. System.out.println("Put: "+n);
  12. notify();
  13.  
  14. }
  15. }
  16.  
  17. class Producer implements Runnable {
  18.  
  19. Counter counter;
  20. Producer(Counter counter){
  21. this.counter = counter ;
  22. new Thread (this,"Producer").start();
  23. }
  24.  
  25. public void run(){
  26. int i = 0;
  27. while(true){
  28. counter.put(i++);
  29. }
  30. }
  31.  
  32. }
  33.  
  34. class Customer implements Runnable{
  35.  
  36. Counter counter ;
  37. public Customer(Counter counter){
  38. this.counter = counter ;
  39. new Thread(this,"Customer").start();
  40. //this.Thread.sleep(10000);
  41. }
  42. public void run (){
  43. while(true){
  44. counter.get();
  45. }
  46. }
  47. }
  48. public class ProducerAndCustomer {
  49. public static void main(String [] args){
  50. Counter counter = new Counter();
  51. new Producer(counter);
  52. new Customer(counter);
  53. System.out.println("haha");
  54. }
  55.  
  56. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值