java多线程通信 例子
Posted 小石头
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java多线程通信 例子相关的知识,希望对你有一定的参考价值。
1 package com.cl.www.thread; 2 3 public class NumberHolder { 4 5 private Integer number = 0; 6 7 // 增加number 8 public synchronized void increaseNum(){ 9 //不是0就不加 10 while(number != 0){ 11 try { 12 this.wait(); 13 } catch (InterruptedException e) { 14 e.printStackTrace(); 15 } 16 } 17 number++; 18 System.out.println("number的值为:"+number); 19 this.notifyAll(); //通知其它线程 20 } 21 22 //减少number 23 public synchronized void decreaseNum(){ 24 //如果等于0就不减少 25 while(number == 0){ 26 try { 27 this.wait(); 28 } catch (InterruptedException e) { 29 e.printStackTrace(); 30 } 31 } 32 number--; 33 System.out.println("number的值为:"+number); 34 this.notifyAll(); //通知其它线程 35 } 36 }
1 package com.cl.www.thread; 2 /** 3 * 4 * 增加number 5 */ 6 public class IncreaseThread implements Runnable{ 7 8 private NumberHolder numberHolder; 9 10 public IncreaseThread(NumberHolder numberHolder) { 11 this.numberHolder = numberHolder; 12 } 13 14 @Override 15 public void run() { 16 int i = 0; 17 while(i<10){ 18 try { 19 Thread.sleep(1000); 20 } catch (InterruptedException e) { 21 e.printStackTrace(); 22 } 23 numberHolder.increaseNum(); 24 i++; 25 } 26 } 27 }
1 package com.cl.www.thread; 2 3 /** 4 * 减少number 5 * 6 */ 7 public class DecreaseThread implements Runnable{ 8 9 private NumberHolder numberHolder; 10 11 public DecreaseThread(NumberHolder numberHolder) { 12 13 this.numberHolder = numberHolder; 14 } 15 @Override 16 public void run() { 17 int i =0; 18 while(i<10){ 19 try { 20 Thread.sleep((long)Math.random()*1000); 21 } catch (InterruptedException e) { 22 e.printStackTrace(); 23 } 24 numberHolder.decreaseNum(); 25 i++; 26 } 27 } 28 }
1 package com.cl.www.thread; 2 3 public class MainTest { 4 public static void main(String[] args) { 5 6 NumberHolder numberHolder = new NumberHolder(); 7 8 IncreaseThread increaseThread = new IncreaseThread(numberHolder); 9 DecreaseThread decreaseThread = new DecreaseThread(numberHolder); 10 11 Thread th1 = new Thread(increaseThread); // 加 number 12 Thread th2 = new Thread(decreaseThread); // 减 number 13 14 Thread th3 = new Thread(increaseThread); // 加 number 15 Thread th4 = new Thread(decreaseThread); // 减 number 16 17 th1.start(); 18 th2.start(); 19 20 th3.start(); 21 th4.start(); 22 } 23 }
输出结果
以上是关于java多线程通信 例子的主要内容,如果未能解决你的问题,请参考以下文章
JAVA多线程提高二:传统线程的互斥与同步&传统线程通信机制