in a program there are multiple resources. And multiple users may be trying to access them at the same time. This will lead to various sort of problems which we have to consider when trying to create that application. That is the basic idea of concurrent process management.
So the main objective to protect resources from multiple user access at once. to do that we may need to use locks and semaphores as we learn in the theories.
Java has built in facility to create semaphores. like java.util.concurrent.Semaphore
here is a simple example of the functionality of semaphore.
Problem : there are equal number of threads which prints A and which print B. We need to print the pattern ABABAB....
import java.util.concurrent.Semaphore; import java.util.logging.Level; import java.util.logging.Logger; public class Handle { // declare and initialize the semaphores private static Semaphore s1 = new Semaphore(0); private static Semaphore s2 = new Semaphore(1); public static void main(String[] args) { // make the threads and make them start. for (int i = 0; i < 10; i++) { new P1(s1, s2).start(); } for (int i = 0; i < 10; i++) { new P2(s1, s2).start(); } } } class P1 extends Thread { private Semaphore s1; private Semaphore s2; public P1(Semaphore s1, Semaphore s2) { this.s1 = s1; this.s2 = s2; } @Override public void run() { try { s2.acquire();// --1 } catch (InterruptedException ex) { Logger.getLogger(P1.class.getName()).log(Level.SEVERE, null, ex); } System.out.print("A"); s1.release(); } } class P2 extends Thread { private Semaphore s1; private Semaphore s2; public P2(Semaphore s1, Semaphore s2) { this.s1 = s1; this.s2 = s2; } @Override public void run() { try { s1.acquire(); } catch (InterruptedException ex) { Logger.getLogger(P2.class.getName()).log(Level.SEVERE, null, ex); } System.out.print("B"); s2.release(); } }
0 comments:
Post a Comment