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

来源:互联网 发布:淘宝卖家入口在哪 编辑:程序博客网 时间:2024/06/05 15:41

一个简单的生产者和消费者的之间的产品流通示例,利用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. }

 

下载: ProducerAndCustomer.java
  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. }
原创粉丝点击