You are on page 1of 2

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

// 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 } };

You might also like