java实现三个线程按指定顺序执行

起三个线程,按指定顺序执行,在需要后执行的线程执行过程中,让前一个线程先执行,即Thread_after中调用Thread_before.jion()

public class ThreadLoop {


    static Thread t1 = new Thread(new Runnable() {
        @SneakyThrows
        @Override
        public void run() {
            System.out.println("t1");
        }
    });


    static Thread t2 = new Thread(new Runnable() {
        @Override
        @SneakyThrows
        public void run() {
            t1.join();// 等t1运行完,继续t2
            System.out.println("t2");
        }
    });


    static Thread t3 = new Thread(new Runnable() {
        @Override
        @SneakyThrows
        public void run() {
            t2.join();// 等t2运行完,继续t3
            System.out.println("t3");
        }
    });


    public static void main(String[] args) {

        t2.start();
        t1.start();
        t3.start();
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值