首页 > 代码库 > java多线程通信 例子
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多线程通信 例子
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。