Java三个线程ABC顺序输出_[Java教程]Java多线程开启三个线程输出ABC10次

[Java教程]Java多线程开启三个线程输出ABC10次

0

2014-10-24 18:00:23

最近学多线程,搜了一下,满屏幕的问题都是类似标题那样的,所以就拿这个当开始吧,自己试了一下手,

多次把电脑CPU跑到100%,终于还是写出来了,大体思路为:

声明一个变量,标记三个线程该哪个线程输出,每次输出将该变量+1,判断方式为 变量对3的余数,如果为1-A,2-B, 3-C1 public class ABC { 2 3 private static int mark = 0; 4 5 private static Object obj = new Object(); 6 7 public static void main(String[] args) throws Exception { 8 ABC abc = new ABC(); 9 new Thread(abc.new PrintA()).start();10 new Thread(abc.new PrintB()).start();11 new Thread(abc.new PrintC()).start();12 }13 14 class PrintA implements Runnable{15 16 @Override17 public void run() {18 for(int i = 0; i < 10; i++){19 synchronized (obj){20 while(mark %3 != 0){21 try {22 obj.wait();23 } catch (InterruptedException e) {24 e.printStackTrace();25 }26 }27 System.out.print("A");28 mark ++;29 obj.notifyAll();30 }31 }32 }33 }34 class PrintB implements Runnable{35 36 @Override37 public void run() {38 for(int i = 0; i < 10; i++){39 synchronized (obj){40 while(mark %3 != 1){41 try {42 obj.wait();43 } catch (InterruptedException e) {44 e.printStackTrace();45 }46 }47 System.out.print("B");48 mark ++;49 obj.notifyAll();50 }51 }52 }53 }54 class PrintC implements Runnable{55 56 @Override57 public void run() {58 for(int i = 0; i < 10; i++){59 synchronized (obj){60 while(mark %3 != 2){61 try {62 obj.wait();63 } catch (InterruptedException e) {64 e.printStackTrace();65 }66 }67 System.out.println("C");68 mark ++;69 obj.notifyAll();70 }71 }72 }73 }74 }

本文网址:http://www.shaoqun.com/a/102924.html

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:admin@shaoqun.com。

JAVA

0

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值