java thread怎么保证线程按顺序执行?如何实现线程排队?

在Java中,通常不保证多个线程按特定顺序执行,因为线程的调度是由操作系统管理的,并且是不可预测的。然而,如果需要确保线程按特定顺序执行,可以使用以下方法:

  1. 使用线程的join()方法:确保一个线程在另一个线程完成之后才开始。
  2. 使用同步工具类:如CountDownLatchCyclicBarrierSemaphore
  3. 使用ReentrantLock和条件变量(Condition)

方法一:使用join()方法

通过调用一个线程的join()方法,当前线程会等待这个线程完成之后再继续执行。

public class JoinExample {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            System.out.println("Thread 1 is running");
        });

        Thread t2 = new Thread(() -> {
            System.out.println("Thread 2 is running");
        });

        Thread t3 = new Thread(() -> {
            System.out.println("Thread 3 is running");
        });

        try {
            t1.start();
            t1.join(); // 等待t1完成

            t2.start();
            t2.join(); // 等待t2完成

            t3.start();
            t3.join(); // 等待t3完成
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

方法二:使用CountDownLatch

CountDownLatch允许一个或多个线程等待其他线程完成某些操作。

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(1);

        Thread t1 = new Thread(() -> {
            System.out.println("Thread 1 is running");
            latch.countDown(); // 计数器减1
        });

        Thread t2 = new Thread(() -> {
            try {
                latch.await(); // 等待计数器减到0
                System.out.println("Thread 2 is running");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

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

 

方法三:使用CyclicBarrier

CyclicBarrier可以让一组线程相互等待,直到到达一个共同的障碍点。

 

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierExample {
    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(3, () -> System.out.println("All threads are ready"));

        Thread t1 = new Thread(() -> {
            try {
                System.out.println("Thread 1 is waiting");
                barrier.await();
                System.out.println("Thread 1 is running");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                System.out.println("Thread 2 is waiting");
                barrier.await();
                System.out.println("Thread 2 is running");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        });

        Thread t3 = new Thread(() -> {
            try {
                System.out.println("Thread 3 is waiting");
                barrier.await();
                System.out.println("Thread 3 is running");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        });

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

 

方法四:使用ReentrantLock和条件变量(Condition)

使用ReentrantLockCondition可以更灵活地控制线程执行顺序。

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockExample {
    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        boolean[] t1Done = {false};

        Thread t1 = new Thread(() -> {
            lock.lock();
            try {
                System.out.println("Thread 1 is running");
                t1Done[0] = true;
                condition.signal();
            } finally {
                lock.unlock();
            }
        });

        Thread t2 = new Thread(() -> {
            lock.lock();
            try {
                while (!t1Done[0]) {
                    condition.await();
                }
                System.out.println("Thread 2 is running");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        });

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆咖啡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值