java多线程编程abc_使用Java 多线程编程 让三个线程轮流输出ABC,循环10次后结束...

简要分析:

要求三个线程轮流输出,这里我们要使用一个对象锁,让关键部分的代码放入同步块当中。同时要有一个变量记录打印的次数到达10次循环后不再打印,另外一个就是要给每个线程一个标志号,我们根据标识号来输出对应的信息。

package com.test;

public class PrintOneTwoThree {

public static void main(String[] args) {

Print p1 = new Print(0);

Print p2 = new Print(1);

Print p3 = new Print(2);

new Thread(p1, "p1").start();

new Thread(p2, "p2").start();

new Thread(p3, "p3").start();

while (Thread.activeCount() > 1)

;

System.out.println("Done!");

}

}

class Print implements Runnable {

private static int state = 0;

private int id;

private static Object lock = new Object();

public Print(int id) {

this.id = id;

}

@Override

public void run() {

synchronized (lock) {

while (state < 30) {

if (state % 3 == id) {

switch (id) {

case 0:

System.out.println("["

+ Thread.currentThread().getName() + "]" + "A");

break;

case 1:

System.out.println("["

+ Thread.currentThread().getName() + "]" + "B");

break;

case 2:

System.out.println("["

+ Thread.currentThread().getName() + "]" + "C");

break;

default:

break;

}

state++;

lock.notifyAll();

} else {

try {

lock.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值