1 class Timer{ 2 private static int num; 3 4 void add(String name){ 5 //synchronized (this){ 6 num++; 7 try{ Thread.sleep(1); } 8 catch(InterruptedException e){}; 9 System.out.println(name+" you are the "+num+" user to use timer!"); 10 //} 11 } 12 } 13 14 15 public class TestSync implements Runnable{ 16 Timer timer = new Timer(); 17 18 public static void main(String[] args) { 19 TestSync t = new TestSync(); 20 21 Thread t1 = new Thread(t,"t1"); 22 Thread t2 = new Thread(t,"t2"); 23 24 25 t1.start(); 26 t2.start(); 27 } 28 29 public void run(){ 30 timer.add(Thread.currentThread().getName()); 31 } 32 }
时间: 2024-11-05 06:26:58