Semaphore in Java
发布时间:2020-12-15 05:35:14 所属栏目:Java 来源:网络整理
导读:Semaphore? 与操作系统概念中的 信号量和PV操作 类似 控制 最大的并发线程数? ? *countdownLatch 也可以实现类似功能 ? Example // java program to demonstrate // use of semaphores Locks import java.util.concurrent.* ; // A shared resource/class. c
Semaphore?与操作系统概念中的 信号量和PV操作 类似 控制最大的并发线程数? ? *countdownLatch也可以实现类似功能 ? Example// java program to demonstrate // use of semaphores Locks import java.util.concurrent.*; //A shared resource/class. class Shared { static int count = 0; } class MyThread extends Thread { Semaphore sem; String threadName; public MyThread(Semaphore sem,String threadName) { super(threadName); this.sem = sem; this.threadName = threadName; } @Override public void run() { // run by thread A if(this.getName().equals("A")) { System.out.println("Starting " + threadName); try { // First,get a permit. System.out.println(threadName + " is waiting for a permit."); // acquiring the lock sem.acquire(); System.out.println(threadName + " gets a permit."); // Now,accessing the shared resource. // other waiting threads will wait,until this // thread release the lock for(int i=0; i < 5; i++) { Shared.count++; System.out.println(threadName + ": " + Shared.count); // Now,allowing a context switch -- if possible. // for thread B to execute Thread.sleep(10); } } catch (InterruptedException exc) { System.out.println(exc); } // Release the permit. System.out.println(threadName + " releases the permit."); sem.release(); } // run by thread B else { System.out.println("Starting " + threadName); try { // First,until this // thread release the lock for(int i=0; i < 5; i++) { Shared.count--; System.out.println(threadName + ": " + Shared.count); // Now,allowing a context switch -- if possible. // for thread A to execute Thread.sleep(10); } } catch (InterruptedException exc) { System.out.println(exc); } // Release the permit. System.out.println(threadName + " releases the permit."); sem.release(); } } } // Driver class public class SemaphoreDemo { public static void main(String args[]) throws InterruptedException { // creating a Semaphore object // with number of permits 1 Semaphore sem = new Semaphore(1); // creating two threads with name A and B // Note that thread A will increment the count // and thread B will decrement the count MyThread mt1 = new MyThread(sem,"A"); MyThread mt2 = new MyThread(sem,"B"); // stating threads A and B mt1.start(); mt2.start(); // waiting for threads A and B mt1.join(); mt2.join(); // count will always remain 0 after // both threads will complete their execution System.out.println("count: " + Shared.count); } } ? ? Starting A
Starting B
A is waiting for a permit.
B is waiting for a permit.
A gets a permit.
A: 1
A: 2
A: 3
A: 4
A: 5
A releases the permit.
B gets a permit.
B: 4
B: 3
B: 2
B: 1
B: 0
B releases the permit.
count: 0
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |