Java后端多线程交替打印的11种方法

一、基础知识

1、八股:线程间同步的五种方式(操作系统/多线程)?

(1)互斥锁(Mutex):采用互斥对象的机制,只有拥有互斥对象的线程才有访问公共资源的权限。因为互斥对象只有一个,所以可以保证公共资源不会被多个线程同时访问呢。比如Java中的synchronized关键字和各种Lock都是这种机制

(2)读写锁(Read-Write Lock):允许多个线程同时读取共享资源,但只有一个线程可以对共享资源进行写操作。

(3)信号量(Semaphore):它允许同一时刻多个线程同时访问同一资源,但是需要控制同一时刻访问此资源的最大线程数。

(4)屏障(Barrier):屏障是一种同步原语,用于等待多个线程到达某个点再一起继续执行。当一个线程到达屏障时,它会停止执行并等待其他线程到达屏障,直到所有线程都达到屏障后,它们才会一起继续执行。比如Java中的CyclicBarrier是这种机制。

(5)事件(Event):Wait/Notify:通过通知操作的方式来保持多线程同步,还可以方便的实现多线程优先级的比较操作。

2、分类

(1)互斥锁(3):LockSupport、ReentrantLock、Sync

(2)读写锁(1):ReentrantReadWriteLock

(3)信号量(2):Semaphore、CountDownLatch

(4)屏障(1):CyclicBarrier

(5)事件(3):Wait/NotifyAll、Join、ReentrantLock+Condition

(6)CAS(1):AtomicInteger

二、代码实现

1、AtomicInteger

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerTest {
    public static AtomicInteger num = new AtomicInteger(1);
    public static int maxNum;
    public static int threadNum;
    public static Thread buildThread(String name, int rest){
        return new Thread(()->{
            while (true){
                if (num.get()%threadNum==rest && num.get()<=100){
                    System.out.println("Thread "+Thread.currentThread().getName()+":"+num);
                    num.incrementAndGet();
                }else if (num.get()>100){
                    break;
                }
            }
        },name);
    }

    public static void main(String[] args) {
        maxNum = 100;
        threadNum = 3;
        for (int i=0;i<threadNum;i++){
            Thread thread = buildThread((i+1)+"", (i+1)%threadNum);
            thread.start();
        }

    }
}

2、CountDownLatch

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;


public class CountDownLatchTest {
    public static volatile int num = 1;
    public static int maxNum = 100;
    public static int threadNum = 3;

    public static Map<String,CountDownLatch> map = new HashMap<>();
    public static class MyThread extends Thread{
        String nextLatch;
        String selfLatch;
        int rest;
        MyThread(String nextLatch, String selfLatch, String name, int rest){
            this.nextLatch = nextLatch;
            this.selfLatch = selfLatch;
            this.rest = rest;
            setName(name);
        }

        @Override
        public void run() {
            while(num<=maxNum){
                map.put(selfLatch,new CountDownLatch(1));
                if (num%threadNum==rest && num<=100){
                    System.out.println("Thread "+getName()+":"+num);
                    num++;
                }
                map.get(nextLatch).countDown();
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        String countDownLatchA = "A";
        String countDownLatchB = "B";
        String countDownLatchC = "C";
        map.put(countDownLatchA,new CountDownLatch(1));
        map.put(countDownLatchB,new CountDownLatch(1));
        map.put(countDownLatchC,new CountDownLatch(1));
        Thread threadA = new MyThread("B","A","1",1);
        Thread threadB = new MyThread("C","B","2",2);
        Thread threadC = new MyThread("A","C","3",0);
        threadC.start();
        threadB.start();
        threadA.start();
    }
}

3、CyclicBarrier

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

public class CyclicBarrierTest {
    public static volatile int num = 1;
    public static int maxNum = 100;
    public static int threadNum = 3;
    public static final CyclicBarrier barrier = new CyclicBarrier(threadNum, new Runnable(){
        @Override
        public void run() {
            num++;
        }
    });
    public static Thread buildThread(String name, int rest){
        return new Thread(()->{
           while (num<=maxNum){
               if (num%threadNum == rest){
                   System.out.println("Thread "+name+":"+num);
               }
               try {
                   barrier.await();
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               } catch (BrokenBarrierException e) {
                   throw new RuntimeException(e);
               }
           }
        });
    }
    public static void main(String[] args) {
        for (int i=threadNum-1;i>=0;i--){
            Thread thread = buildThread((i+1)+"", (i+1)%threadNum);
            thread.start();
        }

    }
}

4、Join

public class JoinTest {
    public static volatile int num;
    public static int maxNum;
    public static int threadNum;

    public static Thread buildThread(Thread beforeThread,String name){
        return new Thread(()->{
            if (beforeThread != null) {
                try {
                    beforeThread.join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            if (num<=100){
                System.out.print("Thread " + Thread.currentThread().getName() + ":" + num + "\n");
                num++;
            }
        },name);
    }

    public static void main(String[] args) throws InterruptedException {
        num = 1;
        maxNum = 100;
        threadNum = 3;
        for (int i=0;i<34;i++){
            Thread threadA = buildThread(null,"A");
            Thread threadB = buildThread(threadA,"B");
            Thread threadC = buildThread(threadB,"C");
            threadC.start();
            threadB.start();
            threadA.start();

            threadC.join();
        }

    }
}

5、LockSupport

import java.util.concurrent.locks.LockSupport;

public class LockSupportTest {
    public static volatile int num;
    public static int maxNum;
    public static int threadNum;
    public static Thread t1 = null;
    public static Thread t2 = null;
    public static Thread t3 = null;
    public static void main(String[] args) {
        num = 1;
        maxNum = 100;
        threadNum = 3;
        t1 = new Thread(()->{
            while (true){
                LockSupport.park();
                if (num<=100 && num%threadNum==1){
                    System.out.print("Thread "+Thread.currentThread().getName()+":"+num+"\n");
                    num++;
                }else if (num>100){
                    LockSupport.unpark(t2);
                    break;
                }
                LockSupport.unpark(t2);
            }
        },"1");
        t2 = new Thread(()->{
            while (true){
                LockSupport.park();
                if (num<=100 && num%threadNum==2){
                    System.out.print("Thread "+Thread.currentThread().getName()+":"+num+"\n");
                    num++;
                }else if (num>100){
                    LockSupport.unpark(t3);
                    break;
                }
                LockSupport.unpark(t3);
            }
        },"2");
        t3 = new Thread(()->{
            while (true){
                LockSupport.park();
                if (num<=100 && num%threadNum==0){
                    System.out.print("Thread "+Thread.currentThread().getName()+":"+num+"\n");
                    num++;
                }else if (num>100){
                    LockSupport.unpark(t1);
                    break;
                }
                LockSupport.unpark(t1);
            }
        },"3");
        t3.start();
        t2.start();
        t1.start();
        LockSupport.unpark(t1);
    }
}

6、ReentrantLock & Condition

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

public class ReentrantLockAndConditionTest {
    public static volatile int num;
    public static ReentrantLock lock;
    public static Condition condition;
    public static int maxNum;
    public static int threadNum;
    public static Thread buildThread(String name){
        return new Thread(()->{
           while(num<=maxNum){
               lock.lock();
               if (num<=maxNum){
                   System.out.print("Thread "+Thread.currentThread().getName()+":"+num+"\n");
                   num++;
               }
               condition.signalAll();
               try {
                   if (num<=maxNum){
                       condition.await();
                   }
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
               lock.unlock();
           }
        },name);
    }
    public static void main(String[] args) {
        num = 1;
        maxNum = 100;
        lock = new ReentrantLock();
        condition = lock.newCondition();
        threadNum = 3;
        Thread threadA = buildThread("A");
        Thread threadB = buildThread("B");
        Thread threadC = buildThread("C");
        threadA.start();
        threadB.start();
        threadC.start();
    }
}

7、ReentrantLock

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest {
    public static volatile int num;
    public static int maxNum;
    public static int threadNum;
    public static ReentrantLock reentrantLock = new ReentrantLock();
    public static Thread buildThread(String name, int rest){
        return new Thread(()->{
            while (true){
                reentrantLock.lock();
                if (num%threadNum==rest && num<=100){
                    System.out.println("Thread "+Thread.currentThread().getName()+":"+num);
                    num++;
                }else if (num>100){
                    reentrantLock.unlock();
                    break;
                }
                reentrantLock.unlock();
            }
        },name);
    }

    public static void main(String[] args) {
        num = 1;
        maxNum = 100;
        threadNum = 3;
        for (int i=0;i<threadNum;i++){
            Thread thread = buildThread((i+1)+"",(i+1)%threadNum);
            thread.start();
        }

    }
}

8、Semaphore

import java.util.concurrent.Semaphore;

public class SemaphoreTest {
    public static volatile int num;
    public static int threadNum;
    public static int maxNum;
    public static Semaphore semaphoreA = new Semaphore(1);
    public static Semaphore semaphoreB = new Semaphore(0);
    public static Semaphore semaphoreC = new Semaphore(0);
    public static class MyThread extends Thread{
        Semaphore cur;
        Semaphore next;
        public MyThread(Semaphore cur, Semaphore next, String name){
            this.cur = cur;
            this.next = next;
            setName(name);
        }

        @Override
        public void run() {
            while(num<=maxNum){
                try {
                    cur.acquire();
                    if (num<=maxNum){
                        System.out.print("Thread "+Thread.currentThread().getName()+":"+num+"\n");
                        num++;
                    }
                    next.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }
    public static void main(String[] args) {
        num = 1;
        threadNum = 3;
        maxNum = 100;
        MyThread threadA = new MyThread(semaphoreA, semaphoreB, "A");
        MyThread threadB = new MyThread(semaphoreB, semaphoreC, "B");
        MyThread threadC = new MyThread(semaphoreC, semaphoreA, "C");
        threadA.start();
        threadB.start();
        threadC.start();
    }
}

9、Sync

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class SyncTest {
    public static volatile int num;
    public static int maxNum;
    public static int threadNum;
    public static final Sync sync = new Sync(0);

    public static Thread buildThread(Sync sync, int initState, String name){
        return new Thread(()->{
            while (true){
                sync.acquire(initState+1);
                if (num<=maxNum){
                    if (num%threadNum==(initState+1)%threadNum){
                        System.out.print("Thread "+Thread.currentThread().getName()+":"+num+"\n");
                        num++;
                    }
                }else{
                    sync.release(initState+1);
                    break;
                }
                sync.release(initState+1);
            }
        },name);
    }

    public static void main(String[] args) {
        num = 1;
        maxNum = 100;
        threadNum = 3;

        for (int i=0;i<threadNum;i++){
            Thread myThread = buildThread(sync, i, (i+1)+"");
            myThread.start();
        }
    }



}
class Sync extends AbstractQueuedSynchronizer{
    Sync(int state){
        setState(state);
    }

    @Override
    public boolean tryAcquire(int arg) {
        if(compareAndSetState(0,arg)) {
            return true;
        }
        return false;
    }

    public boolean tryRelease(int arg) {
        setState(0);
        return true;
    }
}

10、Wait & NotifyAll

public class WaitNotifyAll {
    public static volatile int num;
    public static int totalThreadNum;
    public static int printMaxNum;
    public static final Object obj = new Object();

    public static Thread buildThread(String threadName, int rest){
        return new Thread(()->{
            while (num<=printMaxNum){
                synchronized (obj){
                    if (num%totalThreadNum==rest){
                        obj.notifyAll();
                        System.out.print("Thread "+Thread.currentThread().getName()+":"+num+"\n");
                        num++;
                        try {
                            if (num<=100){
                                obj.wait();
                            }
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }else{
                        obj.notifyAll();
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        },threadName);
    }
    public static void main(String[] args) {
        num = 1;
        totalThreadNum = 3;
        printMaxNum = 100;
        for (int i=0;i<totalThreadNum;i++){
            buildThread((i+1)+"",(i+1)%totalThreadNum).start();
        }
    }
}

11、ReentrantReadWriteLock

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriteLockTest {
    public static volatile int num = 1;
    public static int maxNum = 100;
    public static int threadNum = 3;
    public static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    public static Thread buildThread(String name, int rest){
        return new Thread(()->{
            while (num<=maxNum){
                lock.readLock().lock();
                if (num%threadNum==rest && num<=100){
                    lock.readLock().unlock();
                    lock.writeLock().lock();
                    System.out.println("Thread "+Thread.currentThread().getName()+":"+num);
                    num++;
                    lock.writeLock().unlock();
                    continue;
                }
                lock.readLock().unlock();
            }
        },name);
    }

    public static void main(String[] args) {
        for (int i=0;i<threadNum;i++){
            Thread thread = buildThread((i+1)+"",(i+1)%threadNum);
            thread.start();
        }
    }

}

参考资料:

https://zhuanlan.zhihu.com/p/370130458

https://segmentfault.com/a/1190000041961194

https://segmentfault.com/a/1190000043983105

https://blog.csdn.net/u011403239/article/details/119917362

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值