Wednesday, March 28, 2012

Using the example program material and thread

class TestSinkronisasi {
private java.util.Random random = new java.util.Random();
public void callMe(String data) {
System.out.print("[");
67
try{
Thread.sleep(random.nextInt(200));
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.print(data);
try{
Thread.sleep(random.nextInt(200));
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("]");
}
}
class ThreadBaru extends Thread {
private String data;
private TestSinkronisasi obj;
public ThreadBaru(TestSinkronisasi obj,String data) {
this.obj = obj;
this.data = data;
start();
}
public void run() {
obj.callMe(data);
}
}
class DemoThread {
public static void main(String[] args) {
TestSinkronisasi obj = new TestSinkronisasi();
ThreadBaru thread1 = new ThreadBaru(obj,"Superman");
ThreadBaru thread2 = new ThreadBaru(obj,"Batman");
ThreadBaru thread3 = new ThreadBaru(obj,"Spiderman");
//wait until all the child thread finishes
try{
68
thread1.join();
thread2.join();
thread3.join();
}catch(InterruptedException e) {
System.out.println("The main thread is interrupted " + e);
}
}
}

No comments:

Post a Comment