Java并发编程

Java控制线程执行的先后顺序

2020-10-04  本文已影响0人  Chermack

方式一 wait notify(等待标记)

public class WaitNotify {
    static boolean t2Run = false;
    static final Object lock = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (lock) {
                while (!t2Run) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t1在t2之后执行的代码。。。");
            }
        }, "t1").start();

        new Thread(() -> {
            synchronized (lock) {
                System.out.println("t2已经运行");
                t2Run = true;
                lock.notify();//通知t1运行
            }
        }, "t2").start();
    }
}

方式二Reentranlock(等待标记)

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

public class ThreadSequence {
    static boolean t2Run = false;
    static ReentrantLock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();

    public static void main(String[] args) {
        new Thread(() -> {
            lock.lock();
            try {
                if (!t2Run) condition.await();
                System.out.println("t1...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t1").start();

        new Thread(() -> {
            lock.lock();
            try {
                System.out.println("t2...");
                t2Run = true;
                condition.signal();
            } finally {
                lock.unlock();
            }
        }, "t2").start();
    }
}

方式三park unpark

public class ThreadSequence {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            LockSupport.park();
            System.out.println("t1...");
        }, "t1");

        Thread t2 = new Thread(() -> {
            System.out.println("t2...");
            LockSupport.unpark(t1);
        },"t2");
        t1.start();
        t2.start();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读