在前面了解了线程的同步机制,临界区等,了解了线程的两种基本的同步机制:java
在接下来将要了解到的是更高级的同步机制,主要有如下几种:编程
信号量(semaphore)机制是一个通用的线程同步机制,而其它几个线程同步工具须要根据本身的应用场景选择符合其特性的同步机制;dom
信号量机制其实就是使用一个内部计数器,当该数值大于0时,代表还有能够访问的共享资源,当一个线程进入到临界区时,计数器就会减一,当数值为0时,表示已经没有能够访问的共享资源了,在有线程进来访问将会被挂起;semaphore构造函数中能够传入一个数值,也能够称为”许可“,当该数值为1时,一般称为”binary semphore",由于只有0 和 1 ;编程语言
下面的简单示例中展现了如何使用semaphores同步共享数据;ide
(1)建立一个PrintQueue函数
public class PrintQueue { private final Semaphore semaphore; public PrintQueue() { // binary semaphore this.semaphore = new Semaphore(1); } public void printJob(){ try { semaphore.acquire(); long duration=(long)(Math.random()*10); System.out.printf("%s: PrintQueue: Printing a Job during %d seconds\n", Thread.currentThread().getName(),duration); Thread.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); }finally { semaphore.release(); } } }
public class Job implements Runnable { private PrintQueue printQueue; public Job(PrintQueue printQueue) { this.printQueue = printQueue; } @Override public void run() { System.out.printf("%s: Going to print a job\n", Thread.currentThread().getName()); printQueue.printJob(); System.out.printf("%s: The document has been printed\n", Thread.currentThread().getName()); } }(3)Main
public class Main { public static void main(String[] args) { PrintQueue printQueue=new PrintQueue(); Thread[] threads = new Thread[10]; for (int i = 0; i < 10; i++) { threads[i] = new Thread(new Job(printQueue), "Thread_" + i); } for (int i = 0; i < 10; i++) { threads[i].start(); } } }