java用线程循环打印文字_Java多线程循环打印ABC的5种实现方法

https://blog.csdn.net/weixin_39723337/article/details/80352783题目:3个线程循环打印ABC,其中A打印3次,B打印2次,C打印1次,循环打印2轮一.Synchronized同步法思路:使用synchronized、wait、notifyAll的方法利用线程标记变量控制三个线程的执行顺序。/*** @author XDarker* 201...
摘要由CSDN通过智能技术生成

https://blog.csdn.net/weixin_39723337/article/details/80352783

题目:3个线程循环打印ABC,其中A打印3次,B打印2次,C打印1次,循环打印2轮

一.Synchronized同步法

思路:使用synchronized、wait、notifyAll的方法利用线程标记变量控制三个线程的执行顺序。

/**

* @author XDarker

* 2018-5-17

*/

public class Main {

public static void main(String[] args) throws InterruptedException {

int num = 1;//当前正在执行线程的标记

ABCPrint print = new ABCPrint(num);

Thread threadA = new Thread(new RunnableA(print));

Thread threadB = new Thread(new RunnableB(print));

Thread threadC = new Thread(new RunnableC(print));

threadA.start();

Thread.sleep(500);

threadB.start();

Thread.sleep(500);

threadC.start();

}

}

class RunnableA implements Runnable{

private ABCPrint print;

public RunnableA(ABCPrint print) {

super();

this.print = print;

}

@Override

public void run() {

print.PrintA();

}

}

class RunnableB implements Runnable{

private ABCPrint print;

public RunnableB(ABCPrint print) {

super();

this.print = print;

}

@Override

public void run() {

print.PrintB();

}

}

class RunnableC implements Runnable{

private ABCPrint print;

public RunnableC(ABCPrint print) {

super();

this.print = print;

}

@Override

public void run() {

print.PrintC();

}

}

class ABCPrint {

private int num;//当前正在执行线程的标记

public ABCPrint(int num) {

super();

this.num = num;

}

public void PrintA(){

for (int j = 0; j < 2; j++)//表示 循环打印2轮

synchronized(this){

while(num != 1){

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

for (int i = 0; i < 3; i++) {//表示 打印3次

System.out.println("A");

}

//打印A线程执行完 ,通知打印B线程

num = 2;

this.notifyAll();

}

}

public void PrintB(){

for (int j = 0; j < 2; j++)//表示 循环打印2轮

synchronized(this){

while(num != 2){

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

for (int i = 0; i < 2; i++) {//表示 打印2次

System.out.println("B");

}

//打印B线程执行完 ,通知打印C线程

num = 3;

this.notifyAll();

}

}

public void

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值