1PublicClass TestsyncImplementsrunnable{2 Timer timer =NewTimer ();3PublicStaticvoidMain (String args[]) {4 Testsync test =NewTestsync ();5 Thread t1 =NewThread (test);6 Thread t2 =NewThread (test);7 t1.setname ("T1");8 T2.setname ("T2");9T1.start ();10T2.start ();11}12PublicvoidRun () {13Timer.add (Thread.CurrentThread (). GetName ());14}15}1617Classtimer{18Staticint num = 0;19Publicvoid Add (String name) {20 this; try{23 Thread.Sleep (124} catch (Interruptedexception e) {} 25 System.out.println (name+ ", you are the" +num+ "thread that uses a timer" ); 26 }27 }28}
The results are as follows:
T1, you're the 1th thread to use a timer.
T2, you're the 2nd thread to use a timer.
Own code of The Imitation
1PublicClasstestsync{23PublicStaticvoidMain (String args[]) {4 Runner3 ts1 =NewRunner3 ();5 Runner3 ts2 =NewRunner3 ();6 Thread t1 =NewThread (TS1);7 Thread t2 =NewThread (TS2);8 T1.setname ("T1");9 T2.setname ("T2");10T1.start ();11T2.start ();12}13}1415Class Runner3Implementsrunnable{Timer timer =NewTimer ();17Staticint num = 0;18PublicvoidRun () { synchronized (this) {num++; try{thread.sleep (1); (interruptedexception e) {}System.out.println (Thread.CurrentThread (). GetName () + ", you are the first" + num+ "A thread using a timer"); +}
The result of this operation is:
T1, you're the 2nd thread to use a timer.
T2, you're the 2nd thread to use a timer.
Observing the code of teacher Ma, we found that after implementing the Runnable interface, only new object Test (testsync test = new Testsync ();) and then the same test was passed into thread (). If running on my own is equivalent to new two threads, let two concurrent threads invoke the same run () method. So to get the result of code one,
Runner3 ts1 = new Runner3 (); Runner3 ts2 = new Runner3 (); thread T1 = new Thread (TS1); Thread t2 = new Thread (TS2);
Switch
Runner3 ts = new Runner3 () thread T1 = new Thread (TS); Thread t2 = new Thread (TS);
Can.
Java Learning Record---synchronized