java多线程(10)—顺序打印ABC

越努力越幸运!

 java多线程面试题

public class Test {
 
    public static void main(String[] args) {
        Thread a = new Thread(new Task("A",0));
        Thread b = new Thread(new Task("B",1));
        Thread c = new Thread(new Task("C",2));
        a.start();
        b.start();
        c.start();
    }
     
    static class Task implements Runnable{
         
        private String one;
        private int count;
        private static int num = 0;
         
        public Task(String one,int count){
            this.one = one;
            this.count = count;
        }
         
        @Override
        public void run() {
             
            int i = 0;
            while(i < 10){
                synchronized(Task.class){
                    if(num % 3 == count){
                        num++;
                        System.out.println(one);
                    }else{
                        continue;
                    }
                }
                i++;
            }
        }
    }
}

 lock实现

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java中的多线程机制来实现三个线程按顺序打印ABC。以下是一种可能的实现方式: ```java public class PrintABC { private static final Object lock = new Object(); // 共享锁对象 private static volatile int state = 0; // 当前打印状态,0表示打印A,1表示打印B,2表示打印C public static void main(String[] args) { Thread threadA = new Thread(new PrintThread("A", 0)); Thread threadB = new Thread(new PrintThread("B", 1)); Thread threadC = new Thread(new PrintThread("C", 2)); threadA.start(); threadB.start(); threadC.start(); } static class PrintThread implements Runnable { private String name; private int targetState; public PrintThread(String name, int targetState) { this.name = name; this.targetState = targetState; } @Override public void run() { for (int i = 0; i < 10; i++) { // 打印10次 synchronized (lock) { while (state != targetState) { // 当前状态不是目标状态,等待 try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print(name); // 打印字符 state = (state + 1) % 3; // 更新状态 lock.notifyAll(); // 唤醒其他线程 } } } } } ``` 在上述代码中,我们创建了一个共享的锁对象 `lock` 和一个共享的状态变量 `state`。每个线程在运行时,都会先检查当前的状态是否为目标状态,如果不是则等待,直到状态匹配后打印对应的字符,并更新状态,然后唤醒其他线程。 通过 `Thread.currentThread().getName()` 可以获取当前线程的名字。 以上代码是一种简单的实现方式,但是由于多线程的执行是不确定的,所以打印的结果可能会交错。若要确保按照顺序打印ABC,可以使用信号量(Semaphore)等更高级的同步机制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值