In previous post, we’ve learnt Calling methods in
order using low level wait-notify.
Below we’re using Semarphore concept to achieve the
same.
For problem statement , please refer previous post.
Problem Statement : Making three threads working in way that thread1 calling first(), thread2 calling second() and thread3 calling third()
Problem Statement : Making three threads working in way that thread1 calling first(), thread2 calling second() and thread3 calling third()
public class MyThread extends Thread {
private String method;
private Fooo foo;
public MyThread(Fooo foo, String method) {
this.method = method;
this.foo = foo;
}
/*t1,t2,t3 calling run()*/
public void run() {
if (method == "first") {
foo.first();
} else if (method == "second") {
foo.second();
} else if (method == "third") {
foo.third();
}
}
}
package threads;
import java.util.concurrent.Semaphore;
public class Fooo {
public int pauseTime = 0;
public Semaphore sem1;
public Semaphore sem2;
public Fooo() {
try {
sem1 = new Semaphore(1);
sem2 = new Semaphore(1);
sem1.acquire();
System.out.println("Semaphore 1->"+sem1.availablePermits());
sem2.acquire();
System.out.println("Semaphore 2->"+sem2.availablePermits());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void first() {
try {
System.out.println(Thread.currentThread().getName()+
" Started Executing 1");
Thread.sleep(pauseTime);
System.out.println(Thread.currentThread().getName()+
" Finished Executing 1");
sem1.release();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void second() {
try {
/* block until thread1 release semaphore sem1*/
sem1.acquire();
sem1.release();
System.out.println(Thread.currentThread().getName()+
" Started Executing 2");
Thread.sleep(pauseTime);
System.out.println(Thread.currentThread().getName()+
" Finished Executing 2");
sem2.release();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void third() {
try {
/* we've called acquire() so that third() wait till second()
finish
* and second() finish only when thread2
release semaphore sem2*/
sem2.acquire();
sem2.release();
System.out.println(Thread.currentThread().getName()+
" Started Executing 3");
Thread.sleep(pauseTime);
System.out.println(Thread.currentThread().getName()+
" Finished Executing 3");
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
Fooo foo = new Fooo();
MyThread t1 = new MyThread(foo, "first");
MyThread t2 = new MyThread(foo, "second");
MyThread t3 = new MyThread(foo, "third");
t3.start();
t2.start();
t1.start();
}
}
Output
Thread-0
Started Executing 1
Thread-0
Finished Executing 1
Thread-1
Started Executing 2
Thread-1
Finished Executing 2
Thread-2
Started Executing 3
Thread-2
Finished Executing 3
No comments:
Post a Comment