1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| import java.util.Random ;
public class ThreadOrder {
static int count=0;
public static void main(String[] args) {
Counter ct = new Counter();
Tracker trk1 = new Tracker(ct, "thread one");
Tracker trk2 = new Tracker(ct, "thread two");
trk1.start();
trk2.start();
}
}
class Tracker extends Thread {
Counter ct;
String message;
static private Random trueOrFalse = new Random() ;
Tracker(Counter ct, String msg) {
this.ct = ct;
message = msg;
}
public void run() {
if (trueOrFalse.nextBoolean()) yield() ;
int count = ct.nextCounter() ;
if (trueOrFalse.nextBoolean()) yield() ;
System.out.println(message+ " "+ count);
}
}
class Counter {
private int count=0;
public int nextCounter() {
synchronized(this) {
count++;
return count;
}
}
} |