Condition实现多线程顺序打印
2018-09-05 07:47:24来源:博客园 阅读 ()
Condition实现多线程顺序打印:
1 import java.util.concurrent.locks.Condition; 2 import java.util.concurrent.locks.ReentrantLock; 3 4 public class Run { 5 6 volatile public static int nextPrintWho = 1; 7 private static ReentrantLock lock = new ReentrantLock(); 8 final private static Condition conditionA = lock.newCondition(); 9 final private static Condition conditionB = lock.newCondition(); 10 final private static Condition conditionC = lock.newCondition(); 11 12 public static void main(String[] args) { 13 14 Thread threadA = new Thread() { 15 @Override 16 public void run() { 17 try { 18 lock.lock(); 19 while (nextPrintWho != 1) { 20 conditionA.await(); 21 } 22 for (int i = 0; i < 3; i++) { 23 System.out.println("ThreadA " + (i+1)); 24 } 25 nextPrintWho = 2; 26 conditionB.signalAll(); 27 } catch (InterruptedException e) { 28 e.printStackTrace(); 29 }finally { 30 lock.unlock(); 31 } 32 }; 33 }; 34 Thread threadB = new Thread() { 35 @Override 36 public void run() { 37 try { 38 lock.lock(); 39 while (nextPrintWho != 2) { 40 conditionB.await(); 41 } 42 for (int i = 0; i < 3; i++) { 43 System.out.println("ThreadB " + (i+1)); 44 } 45 nextPrintWho = 3; 46 conditionC.signalAll(); 47 } catch (InterruptedException e) { 48 e.printStackTrace(); 49 }finally { 50 lock.unlock(); 51 } 52 }; 53 }; 54 Thread threadC = new Thread() { 55 @Override 56 public void run() { 57 try { 58 lock.lock(); 59 while (nextPrintWho != 3) { 60 conditionC.await(); 61 } 62 for (int i = 0; i < 3; i++) { 63 System.out.println("ThreadC " + (i+1)); 64 } 65 nextPrintWho = 1; 66 conditionA.signalAll(); 67 } catch (InterruptedException e) { 68 e.printStackTrace(); 69 }finally { 70 lock.unlock(); 71 } 72 }; 73 }; 74 Thread[] aArray = new Thread[5]; 75 Thread[] bArray = new Thread[5]; 76 Thread[] cArray = new Thread[5]; 77 for (int i = 0; i < 5; i++) { 78 aArray[i] = new Thread(threadA); 79 bArray[i] = new Thread(threadB); 80 cArray[i] = new Thread(threadC); 81 aArray[i].start(); 82 bArray[i].start(); 83 cArray[i].start(); 84 } 85 } 86 }
运行结果如下:
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- DES/3DES/AES 三种对称加密算法实现 2020-06-11
- SpringBoot + Vue + ElementUI 实现后台管理系统模板 -- 后 2020-06-10
- Spring Boot 实现定时任务的 4 种方式 2020-06-10
- JSP+SSH+Mysql+DBCP实现的租车系统 2020-06-09
- Java实现的三种字符串反转 2020-06-09
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash