實(shí)現(xiàn)方式
1、使用Thread.join()方法;
2、使用計(jì)數(shù)器CountDownLatch
3、使用原子類AtomicInteger
4、使用volatile關(guān)鍵字
5、使用synchronized關(guān)鍵字
6、使用Lock
7、調(diào)用Thread的靜態(tài)方法sleep()-暴力解法
public class KCthreads {
//怎么保證線程執(zhí)行順序?
private volatile static int v = 0; //[解法4使用]
private static int s = 0;
public static void main(String[] args) throws InterruptedException {
//【解法1:】join()方法:將線程并行變?yōu)榇?// Thread t1 = new Thread(() -> test(), "線程A");
// Thread t2 = new Thread(() -> test(), "線程B");
// Thread t3 = new Thread(() -> test(), "線程C");
// t1.start();t1.join();
// t2.start();t2.join();
// t3.start();
//【解法2:】CountDownLatch計(jì)數(shù)器
// CountDownLatch count = new CountDownLatch(2);
// new Thread(() -> {
// test();
// count.countDown();
// }, "線程A").start();
// new Thread(()->{ //匿名內(nèi)部類,也就是重寫run()方法
// while (count.getCount() == 2){
//
// }
// count.countDown();
// test();
// },"線程B").start();
// new Thread(()->{ //匿名內(nèi)部類,也就是重寫run()方法
// while (count.getCount() == 1){
//
// }
// test();
// },"線程C").start();
//【解法3:】AtomicInteger原子類
// AtomicInteger atomic = new AtomicInteger(0);
// new Thread(() -> {
// test();
// atomic.incrementAndGet(); //自增i++
// }, "線程A").start();
// new Thread(()->{ //匿名內(nèi)部類,也就是重寫run()方法
// while (atomic.get() == 0){
//
// }
// atomic.incrementAndGet();
// test();
// },"線程B").start();
// new Thread(()->{ //匿名內(nèi)部類,也就是重寫run()方法
// while (atomic.get() == 1){
//
// }
// atomic.incrementAndGet();
// test();
// },"線程C").start();
//【解法4:】使用volatile關(guān)鍵字
// new Thread(()->{
// test();
// v = 1;
// },"線程A").start();
// new Thread(()->{
// while(v == 0){
//
// }
// test();
// v = 2;
// },"線程B").start();
// new Thread(()->{
// while(v == 1){
//
// }
// test();
// },"線程C").start();
//【解法5:】使用synchronized關(guān)鍵字
// new Thread(()->{
// test();
// s++;
// },"線程A").start();
// new Thread(()->{
// synchronized (KCthreads.class){
// while (s == 0){
//
// }
// test();
// s++;
// }
// },"線程B").start();
// new Thread(()->{
// synchronized (KCthreads.class){
// while (s == 1){
//
// }
// test();
// }
// },"線程C").start();
//【解法6:】使用鎖Lock:ReentrantLock
// Lock lock = new ReentrantLock();
// new Thread(()->{
// test();
// },"線程A").start();
// new Thread(()->{
// lock.lock();
// test();
// lock.unlock();
// },"線程B").start();
// new Thread(()->{
// lock.lock();
// test();
// lock.unlock();
// },"線程C").start();
//【解法7:】最暴力解法:sleep
Thread t1 = new Thread(() -> test(), "線程A");
Thread.sleep(1000);
t1.start();
Thread t2 = new Thread(() -> test(), "線程B");
Thread.sleep(1000);
t2.start();
Thread t3 = new Thread(() -> test(), "線程C");
Thread.sleep(1000);
t3.start();
}
private static void test() {
System.out.println(Thread.currentThread().getName());
}
//打印結(jié)果:順序打印
// 線程A
// 線程B
// 線程C
}