Professional Documents
Culture Documents
// ThreadSync.java class MyThread extends Thread { static String message[]={"I","love","Java."}; public MyThread(String id) { // Gi hm dng (constructor) ca lp Thread cha super(id); } public void run() { Sync.displayList(getName(), message); } void waiting() { try { sleep(2000); } catch(InterruptedException e){ System.out.println("Interrupted"); } } }; class Sync { public static synchronized void displayList(String name, String list[]) { /* Nu khng dng t kha synchronized th s khng m bo mt lung lm xong ht cng vic ca n ri mt lung khc mi c bt u chy. */ for (int i=0; i< list.length; ++i) { MyThread thread = (MyThread)Thread.currentThread(); // Hm waiting nh ngha trn thread.waiting(); System.out.println(name + list[i]); } } }; public class ThreadSync { public static void main(String args[]) { MyThread thread1 = new MyThread("Thread 1: ");
35 36 37 38 39 40 41 42 43 44 45
MyThread thread2 = new MyThread("Thread 2: "); thread1.start(); // Hm run ca thread1 c gi thread2.start(); // Hm run ca thread2 c gi } };