目录页:https://blog.csdn.net/u011294519/article/details/88367808
1.Semaphore
当一个线程想要访问一个由semaphore保护的共享资源时,首先,它必须获取semaphore。如果semaphore的内部计数器大于0,则semaphore对计数器进行递减,并允许访问共享资源。如果semaphore的计数器为0,则semaphore将线程休眠,直到计数器大于0。
显然,semaphore不仅仅是计数器。当计数器的值为零时,它们可以让线程等待,也就是说,它们充当具有计数器功能的锁。
1.1.Semaphore主要方法
Semaphore(int permits):构造方法,创建具有给定许可数的计数信号量并设置为非公平信号量。
Semaphore(int permits,boolean fair):构造方法,当fair等于true时,创建具有给定许可数的计数信号量并设置为公平信号量。
void acquire():从此信号量获取一个许可前线程将一直阻塞。
void acquire(int n):从此信号量获取给定数目许可,在提供这些许可前一直将线程阻塞。
void release():释放一个许可,将其返回给信号量。就如同车开走返回一个车位。
void release(int n):释放n个许可。
int availablePermits():当前可用的许可数。
1.2.示例代码
以打印机为例子,假设有3台打印机,这时打印机资源就是共享资源,所以构造semaphore时传入参数为3
打印机队列类,这个类有3个主要属性,它们控制从3个打印机中选择一个空闲打印机并锁定它来打印作业的逻辑。
package com.concurrent.coline.part6.semaphore.printer;
import java.util.Date;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class PrinterQueue {
//This Semaphore will keep track of no. of printers used at any point of time.
private final Semaphore semaphore;
//While checking/acquiring a free printer out of three available printers, we will use this lock.
private final Lock printerLock;
//This array represents the pool of free printers.
private boolean freePrinters[];
public PrinterQueue() {
semaphore = new Semaphore(3);
freePrinters = new boolean[3];
for (int i = 0; i < 3; i++) {
freePrinters[i] = true;
}
printerLock = new ReentrantLock();
}
public void printJob() {
try {
//Decrease the semaphore counter to mark a printer busy
System.out.printf("Now wait queue num : %s \n", semaphore.getQueueLength());
semaphore.acquire();
System.out.printf("when %s in available permites %s \n", Thread.currentThread().getName(), semaphore.availablePermits());
//Get the free printer
int assignedPrinter = getPrinter();
//Print the job
Long duration = (long) (Math.random() * 10000);
System.out.println(Thread.currentThread().getName()
+ ": Printer " + assignedPrinter
+ " : Printing a Job during " + (duration / 1000)
+ " seconds :: Time - " + new Date());
Thread.sleep(duration);
//Printing is done; Free the printer to be used by other threads.
releasePrinter(assignedPrinter);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.printf("%s: The document has been printed\n", Thread
.currentThread().getName());
//Increase the semaphore counter back
semaphore.release();
}
}
//Acquire a free printer for printing a job
private int getPrinter() {
int foundPrinter = -1;
try {
//Get a lock here so that only one thread can go beyond this at a time
printerLock.lock();
//Check which printer is free
for (int i = 0; i < freePrinters.length; i++) {
//If free printer found then mark it busy
if (freePrinters[i]) {
foundPrinter = i;
freePrinters[i] = false;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//Allow other threads to check for free priniter
printerLock.unlock();
}
return foundPrinter;
}
//Release the printer
private void releasePrinter(int i) {
printerLock.lock();
//Mark the printer free
freePrinters[i] = true;
printerLock.unlock();
}
}
打印类
package com.concurrent.coline.part6.semaphore.printer;
public class PrintingJob implements Runnable {
private PrinterQueue printerQueue;
public PrintingJob(PrinterQueue printerQueue) {
this.printerQueue = printerQueue;
}
@Override
public void run() {
System.out.printf("%s: Going to print a document\n", Thread
.currentThread().getName());
printerQueue.printJob();
}
}
测试类
package com.concurrent.coline.part6.semaphore.printer;
public class Apptest {
public static void main(String[] args) {
PrinterQueue printerQueue = new PrinterQueue();
Thread thread[] = new Thread[10];
for (int i = 0; i < 10; i++) {
thread[i] = new Thread(new PrintingJob(printerQueue), "Thread " + i);
}
for (int i = 0; i < 10; i++) {
thread[i].start();
}
}
}
源码在concurrent-toolbar模块的part6
因为打印了太多东西,执行结果我就不截图出来了
1.3.查看源码环节
构造方法:一路进入源码,发现最终是使用AQS的setStatus方法,这个跟CountDownLatch是一样的
这个status是使用volatile关键字修饰,在我之前的博文说过,保证可见性,不保证原子性。
acquire()方法: 一路进入方法
在这里semaphore获取剩余资源量,并重新设置state,这里的AQS的compareAndSetState写法看上去很神奇,以后写代码可以参考。
release()方法:
还是一路进代码
发现大神很喜欢使用自旋来保证代码执行,我在平时写代码时除了获取kafka消息时基本不敢使用死循环,总感觉怕怕的。
2.FutureTask
2.1.主要方法
- public FutureTask(Callable<V> callable),这个是我们经常用的构造方法,传入Callable创建一个FutureTask,Callable有返回值,可以抛出异常。
- public FutureTask(Runnable runnable, V result),这个构造函数很有意思,如果使用这个构造函数创建出FutureTask,在get的时候其实返回的是传入的result,个人理解是在你想使用runnable(不需要返回值,不需要抛出异常)的时候,需要满足线程的并发执行,又要保证线程全部执行完成后再执行后续业务代码时使用。
- get():获取线程执行完成的返回值
- cancel():中断FutureTask,注意,java的线程都是协作式的,所以这边的cancel并不是说调用了就干掉这个FutureTask实例,而是设置该实例的state值作为标识,这个有兴趣的可以看源码。
2.2.示例代码
package com.concurrent.coline.part6.future;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* 类说明:演示Future等的使用
*/
public class UseFuture {
/*实现Callable接口,允许有返回值*/
private static class UseCallable implements Callable<Integer> {
private int sum;
@Override
public Integer call() throws Exception {
System.out.println("Callable子线程开始计算");
Thread.sleep(2000);
for (int i = 0; i < 5000; i++) {
sum = sum + i;
}
System.out.println("Callable子线程计算完成,结果=" + sum);
return sum;
}
}
private static class UseRunnable implements Runnable {
private int sum;
@Override
public void run() {
System.out.println("UseRunnable子线程开始计算");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 5000; i++) {
sum = sum + i;
}
}
}
public static void main(String[] args)
throws InterruptedException, ExecutionException {
UseCallable useCallable = new UseCallable();
FutureTask<Integer> futureTask = new FutureTask<>(useCallable);
new Thread(futureTask).start();
Random r = new Random();
//随机决定是获得结果还是终止任务
if (r.nextBoolean()) {
System.out.println("Get UseCallable result = " + futureTask.get());
} else {
System.out.printf("中断计算 flag: %s \n", futureTask.cancel(true));
}
/*
个人理解使用runnable初始化FutureTask目的是为了并发执行线程的同时保证后续的业务执行顺序
*/
UseRunnable useRunnable = new UseRunnable();
FutureTask<Integer> runnableFutureTask = new FutureTask(useRunnable, 1);
new Thread(runnableFutureTask).start();
System.out.println("runnableFutureTask get " + runnableFutureTask.get());
System.out.println("main ended");
}
}
源码在concurrent-toolbar模块的part6
运行结果: