如何确保三个线程顺序执行

三个线程t1、t2、t3。确保三个线程,t1 执行完后 t2 执行,t2 执行完后 t3 执行。

一、使用 CountDownLatch

二、使用 join

thread.join 把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程 A 中调用了线程 B 的 join(),直到线程 B 执行完毕后,才会继续执行线程 A。

public class ThreadTest1 {
    // T1、T2、T3三个线程顺序执行
    public static void main(String[] args) {
        Thread t1 = new Thread(new Work(null));
        Thread t2 = new Thread(new Work(t1));
        Thread t3 = new Thread(new Work(t2));
        t1.start();
        t2.start();
        t3.start();
    }

    static class Work implements Runnable {
        private Thread beforeThread;
        public Work(Thread beforeThread) {
            this.beforeThread = beforeThread;
        }
        public void run() {
            if (beforeThread != null) {
                try {
                    beforeThread.join();
                    System.out.println("thread start:" + Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("thread start:" + Thread.currentThread().getName());
            }
        }
    }
}

三、CachedThreadPool

FutureTask 一个可取消的异步计算。FutureTask 实现了 Future 的基本方法,提空 start cancel 操作,可以查询计算是否已经完成,并且可以获取计算的结果。结果只可以在计算完成之后获取, get 方法会阻塞当计算没有完成的时候,一旦计算已经完成,那么计算就不能再次启动或是取消。

一个 FutureTask 可以用来包装一个 Callable 或是一个 runnable 对象。因为 FurtureTask 实现了 Runnable 方法,所以一个 FutureTask 可以提交(submit)给一个 Excutor 执行(excution)。

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class ThreadTest3 {

    // T1、T2、T3三个线程顺序执行
    public static void main(String[] args) {
        FutureTask future1 = new FutureTask(new Work(null));
        Thread t1 = new Thread(future1);

        FutureTask future2 = new FutureTask(new Work(future1));
        Thread t2 = new Thread(future2);

        FutureTask future3 = new FutureTask(new Work(future2));
        Thread t3 = new Thread(future3);

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

    static class Work implements Callable {
        private FutureTask beforeFutureTask;

        public Work(FutureTask beforeFutureTask) {
            this.beforeFutureTask = beforeFutureTask;
        }

        public Integer call() throws Exception {
            if (beforeFutureTask != null) {
                Integer result = beforeFutureTask.get();//阻塞等待
                System.out.println("thread start:" + Thread.currentThread().getName());
            } else {
                System.out.println("thread start:" + Thread.currentThread().getName());
            }
            return 0;
        }
    }
}

四、使用阻塞队列(BlockingQueue)

阻塞队列(BlockingQueue)是java util.concurrent包下重要的数据结构。BlockingQueue 提供了线程安全的队列访问方式:当阻塞队列进行插入数据时,如果队列已满,线程将会阻塞等待直到队列非满;从阻塞队列取数据时,如果队列已空,线程将会阻塞等待直到队列非空。并发包下很多高级同步类的实现都是基于 BlockingQueue 实现的。

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ThreadTest4 {
    
    // T1、T2、T3三个线程顺序执行
    public static void main(String[] args) {
        //blockingQueue保证顺序
        BlockingQueue blockingQueue = new LinkedBlockingQueue();
        Thread t1 = new Thread(new Work());
        Thread t2 = new Thread(new Work());
        Thread t3 = new Thread(new Work());

        blockingQueue.add(t1);
        blockingQueue.add(t2);
        blockingQueue.add(t3);

        for (int i = 0; i < 3; i++) {
            Thread t = null;
            try {
                t = blockingQueue.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            t.start();
            //检测线程是否还活着
            while (t.isAlive()) ;
        }
    }

    static class Work implements Runnable {
        public void run() {
            System.out.println("thread start:" + Thread.currentThread().getName());
        }
    }
}

五、使用单个线程池

newSingleThreadExecutor 返回一个包含单线程的 Executor,将多个任务交给此 Executor 时,这个线程处理完一个任务后接着处理下一个任务,若该线程出现异常,将会有一个新的线程来替代。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadTest5 {

    public static void main(String[] args) {
        final Thread t1 = new Thread(new Runnable() {
            public void run() {
                System.out.println(Thread.currentThread().getName() + " run 1");
            }
        }, "T1");
        final Thread t2 = new Thread(new Runnable() {
            public void run() {
                System.out.println(Thread.currentThread().getName() + " run 2");
                try {
                    t1.join(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "T2");
        final Thread t3 = new Thread(new Runnable() {
            public void run() {
                System.out.println(Thread.currentThread().getName() + " run 3");
                try {
                    t2.join(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "T3");

        //使用 单个任务的线程池来实现。保证线程的依次执行
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(t1);
        executor.submit(t2);
        executor.submit(t3);
        executor.shutdown();
    }
}

三个线程轮流打印1-100

六、synchronized关键字实现

public class MyThread1 implements Runnable {

    private static Object lock = new Object();
    private static int count;
    private int no;

    public MyThread1(int no) {
        this.no = no;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (lock) {
                if (count > 100) {
                    break;
                }
                if (count % 3 == this.no) {
                    System.out.println(Thread.currentThread().getName() + "\t" + this.no + "\t" + count);
                    count++;
                } else {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                lock.notifyAll();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new MyThread1(0), "A");
        Thread t2 = new Thread(new MyThread1(1), "B");
        Thread t3 = new Thread(new MyThread1(2), "C");
        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();
    }
}

七、ReentrantLock实现一

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

public class MyThread2 implements Runnable {

    private static ReentrantLock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();
    private static int count;
    private int no;

    public MyThread2(int no) {
        this.no = no;
    }

    @Override
    public void run() {
        while (true) {
            lock.lock();
            if (count > 100) {
                break;
            } else {
                if (count % 3 == this.no) {
                    System.out.println(this.no + "-->" + count);
                    count++;
                } else {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            condition.signalAll();
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new MyThread2(0));
        Thread t2 = new Thread(new MyThread2(1));
        Thread t3 = new Thread(new MyThread2(2));
        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();
    }
}

八、ReentrantLock 实现二

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

public class Testmain {
    public static void main(String[] args) {

        Alternate an = new Alternate();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 33; i++) {
                    an.logA(i);
                }
            }
        }, "A").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 33; i++) {
                    an.logB(i);
                }
            }
        }, "B").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 33; i++) {
                    an.logC(i);
                    System.out.println("--------------------------------");
                }
            }
        }, "C").start();
    }
}

class Alternate {

    private static int num = 1;
    private int tempA = 0;
    private int tempB = 0;
    private int tempC = 0;
    Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void logA(int total) {
        lock.lock();
        try {
            if (num != 1 && num != (tempA + 3)) {
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + num + "\t" + total);
            tempA = num;
            num++;
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void logB(int total) {
        lock.lock();
        try {
            if (num != 2 && num != (tempB + 3)) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + num + "\t" + total);
            tempB = num;
            num++;
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void logC(int total) {
        lock.lock();
        try {
            if (num != 3 && num != (tempC + 3)) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + num + "\t" + total);
            tempC = num;
            num++;
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

你可能感兴趣的:(如何确保三个线程顺序执行)