a counter (not a real object) to keep several Threads synchronize by ordering
Semaphore mutex_b = new Semaphore(1,fairness);
fareness=false (default) :no Guarantee to serve fairly oher Threads (which not invoking acquire())
fareness=true : Guarantee to select first which that acquire a permit (by invoking acquire()).but no guarantee on which one will be served first!
public class Foo {
public Foo(){};
//final Semaphore mutex_a = new Semaphore(0);
final Semaphore mutex_b = new Semaphore(1,true);//true=fair , false=unfair
MyThreadA a;
MyThreadB b;
MyThreadC c;
Object sycObject=new Object();
public void A(final int n , final int m)//print from n to m
{
a=new MyThreadA(sycObject,n,m);
a.start();
}
public void B(final int n , final int m)//print from n to m
{
b=new MyThreadB(sycObject,n,m);
b.start();
}
public void C(final int n , final int m)//print from n to m
{
c=new MyThreadC(sycObject,n,m);
c.start();
}
class MyThreadA extends Thread{
Object mSyncObj;
int M,N;
MyThreadA(Object syncObj,int n,int m)
{
mSyncObj=syncObj;
M=m;
N=n;
}
@Override
public void run()
{
String output="";
for(int i=N;i<=M;i++){
output+=String.valueOf(i)+",";
}
Log.d("##THREAD##", output);
// mutex_a.release();
/* synchronized (mSyncObj) {
mSyncObj.notify();
}*/
}
}
class MyThreadB extends Thread {
Object mSyncObj;
int M, N;
MyThreadB(Object syncObj, int n, int m) {
mSyncObj = syncObj;
M = m;
N = n;
}
@Override
public void run() {
try {
mutex_b.acquire();
} catch (Exception ex) {
}
String output = "";
for (int i = N; i <= M; i++) {
output += String.valueOf(i) + ",";
}
Log.d("##THREAD##", output);
mutex_b.release();
}
}
class MyThreadC extends Thread {
Object mSyncObj;
int M, N;
MyThreadC(Object syncObj, int n, int m) {
mSyncObj = syncObj;
M = m;
N = n;
}
@Override
public void run() {
try {
mutex_b.acquire();
} catch (InterruptedException ex) {
}
String output = "";
for (int i = N; i <= M; i++) {
output += String.valueOf(i) + ",";
}
Log.d("##THREAD##", output);
mutex_b.release();
}
}
}