a,b,c三个线程同时启动,a线程打印a,b线程打印b,c线程打印c,如何用Java代码实现按顺序打印abc,循环十次。

利用 Locksupport的两个方法:
    park(): 阻塞当前线程
    unpark(thread): 唤醒指定线程

public static void main(String[] args) {
		Thread a,b,c;
		a = new Thread(() -> {
			LockSupport.park();
			for(int i=0;i<10;i++){
				System.out.print(Thread.currentThread().getName());
				LockSupport.park();
			}
		},"a");
		b = new Thread(() -> {
			LockSupport.park();
			for(int i=0;i<10;i++){
				System.out.print(Thread.currentThread().getName());
				LockSupport.park();
			}
		},"b");
		c = new Thread(() -> {
			LockSupport.park();
			for(int i=0;i<10;i++){
				System.out.print(Thread.currentThread().getName());
				LockSupport.park();
			}
		},"c");
		a.start();
		b.start();
		c.start();
		int count = 1;
		for(;;){
			if(!a.isAlive() && !b.isAlive() && !c.isAlive()){
				break;
			}
			if(count%3 == 1){
				LockSupport.unpark(a);
			}
			if(count%3 == 2){
				LockSupport.unpark(b);
			}
			if(count%3 == 0){
				LockSupport.unpark(c);
			}
			try {
                // 主线程休眠10毫秒是为了把cpu的使用权让给 a/b/c 线程
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			count++;
		}
	}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
当然,我可以帮你编写一个Java程序,用三个线程循环打印a、b、c。以下是一个简单的实现示例: ```java class PrintThread implements Runnable { private static final Object lock = new Object(); private static volatile char currentChar = 'a'; private char printChar; public PrintThread(char printChar) { this.printChar = printChar; } @Override public void run() { for (int i = 0; i < 10; i++) { synchronized (lock) { while (currentChar != printChar) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print(printChar); if (currentChar == 'c') { System.out.println(); // 换行 } currentChar = (char) (currentChar + 1 > 'c' ? 'a' : currentChar + 1); lock.notifyAll(); } } } } public class Main { public static void main(String[] args) { Thread threadA = new Thread(new PrintThread('a')); Thread threadB = new Thread(new PrintThread('b')); Thread threadC = new Thread(new PrintThread('c')); threadA.start(); threadB.start(); threadC.start(); } } ``` 上述代码中,我们定义了一个名为`PrintThread`的线程类,它实现了`Runnable`接口。每个线程都会打印一个特定的字符,共循环打印10次。通过`synchronized`关键字和`wait()`、`notifyAll()`方法来实现线程间的同步和互斥。在`run()`方法中,每个线程会判断当前应该打印的字符是否为自己负责打印的字符,如果不是,则线程进入等待状态。当轮到自己打印时,输相应的字符,并使用`notifyAll()`方法唤醒其他线程。最后,主函数中创建三个线程,并启动它们。 运行以上代码,你会看到输结果为: ``` abc abc abc ... ``` 希望这能帮到你!如果你还有其他问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值