其他分享
首页 > 其他分享> > 5.线程同步辅助类

5.线程同步辅助类

作者:互联网

线程同步辅助类

线程同步辅助类

Semaphore

Semaphore(信号量)是一种计数器,用来保护一个或者多个共享资源的访问

Semaphore接收一个int类型的整数,表示可以获取共享资源访问的次数
如:Semaphore semaphore = new Semaphore(3);
当调用semaphore.acquire()方法,信号量减去1,当信号量为0的时候,访问的线程进入等待状态

示例代码:

package javalearn.thread.helper;

import java.util.concurrent.Semaphore;

public class SemaphoreTest {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        Thread t1 = new Thread(new Print(semaphore));
        Thread t2 = new Thread(new Print(semaphore));
        Thread t3 = new Thread(new Print(semaphore));
        Thread t4 = new Thread(new Print(semaphore));
        t1.start();
        t2.start();
        t3.start();
        //等待前3个线程任意一个释放才会执行
        t4.start();
    }
}

class Print implements Runnable {

    private Semaphore semaphore;

    public Print(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        print();
    }

    private void print() {
        try {
            semaphore.acquire();
            System.out.println("打印....需要3s");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }
}

Semaphore还有其他的两个acquire()方法
acquireUninterruptibly(): 它其实就是acquire()方法。当信号量的内部计数器为0的时候,信号量会阻塞线程直到其被释放。线程在被堵塞的这段时间中,可能会被中断,从而导致acquire()方法抛出InterruptedException异常。而acquireUninterruptibly会忽略线程的中断并且不会抛出任何异常

**tryAcquire()

标签:同步,辅助,Thread,void,phaser,线程,new,public
来源: https://blog.csdn.net/u013425841/article/details/115600666