Tuesday, November 29, 2016

import java.util.LinkedList;

import java.util.Queue;



public class ThreadOrderingJoin {

static Queue q = new LinkedList<>();

static int count = 10;

static Object monitor = new Object();



static class MyThread extends Thread {

int p ;


public int getP() {

return p;


}


public void setP(int p) {

this.p = p;


}


public MyThread(int p) {

super();

this.p = p;


}


public void run() {

while (true) {

try {

synchronized (monitor) {


if (!q.isEmpty()) {

MyThread t = (MyThread) q.poll();

if (t.getId() != this.getId()){

t.start();

monitor.wait();

System.out.println(this.getName()+" join on "+t.getName());

t.join();

// System.out.println( " >>>>>>>"+ t.getP());


}
} else {

// System.out.println( " >>>>>>>"+ this.getP());

System.out.println( this.getName() +" unjoin on ");

monitor.notifyAll();

break;


}

}
} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();


}

}
System.out.println( " >>>>>>>"+ this.getP());


}

}


public static void main(String[] args) {

MyThread T1 = new MyThread(1);

MyThread T2 = new MyThread(2);

MyThread T0 = new MyThread(3);



q.add(T2);

q.add(T1);

// q.add(T0);



// T1.start();

// T2.start();

T0.start();



try {

System.out.println(" main join on " +T0.getName());



T0.join();

System.out.println(" main unjoin on "+T0.getName());



} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();


}



}

}

No comments:

Post a Comment