Therefore, I think that this signal class if it can return the number, but also know which objects are waiting, which resources can be used, is very perfect, only to get these general figures, the precise control is not very significant. No better use has been thought of yet.
Here is a simple example:
import Java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import Java.util.concurrent.Semaphore;
/**
* Java thread: New feature-Semaphore
*
* @author leizhimin
*/
public class Test {
public static void Main (string[] args) {
Mypool mypool = new Mypool (20);
//Create thread pool
Executorservice ThreadPool = Executors.newfixedthreadpool (2);
mythread t1 = new Mythread ("Task A", Mypool, 3);
mythread t2 = new Mythread ("Task B", Mypool, 12);
mythread t3 = new Mythread ("Task C", Mypool, 7);
//thread pool to perform tasks
Threadpool.execute (t1);
Threadpool.execute (T2);
Threadpool.execute (T3);
//Close pool
Threadpool.shutdown ();
}
}
/**
* A pool
*/
class Mypool {
private semaphore SP; Pool-related signal volume
/**
* The size of the pool, which is passed to the semaphore
*
* @param sizes of size pools
*/
mypool (int size) {
this.sp = new semaphore (size);
}
public semaphore getsp () {
return SP;
}
public void setsp (semaphore sp) {
this.sp = SP;
}
}
class Mythread extends Thread {
private String ThreadName; The name of the thread
private Mypool pool; Custom Pool
private int x; The size of the application semaphore
mythread (String threadname, Mypool Pool, int x) {
this.threadname = ThreadName;
this.pool = pool;
this.x = x;
}
public void Run () {
try {
///Get a given number of licenses from this semaphore
POOL.GETSP (). Acquire (x);
//todo: Perhaps there is more complex business to be done here
System.out.println (ThreadName +) successfully acquired "+ x +" License! ");
} catch (Interruptedexception e) {
E.printstacktrace ();
} finally {
//Frees a given number of licenses and returns them to the semaphore.
pool.getsp (). Release (x);
System.out.println (ThreadName + "released" + x +) license! ");
}
}
}
任务B成功获取了12个许可!
任务B释放了12个许可!
任务A成功获取了3个许可!
任务C成功获取了7个许可!
任务C释放了7个许可!
任务A释放了3个许可!
Process finished with exit code 0
As can be seen from the result, the semaphore is only to monitor the pool resources, but does not guarantee the thread security, therefore, in use, should control the thread's secure access pool resources.
Source: http://lavasoft.blog.51cto.com/62575/222469