public class TestSync implements Runnable
{
Timer timer=new Timer();
public void run()
{
timer.add(Thread.currentThread().getName());
}
public static void main(String[] args)
{
TestSync test=new TestSync();
Thread t1=new Thread(test);
Thread t2=new Thread(test);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
class Timer
{
public static int num=0;
//synchronized锁定一段代码,含义:当执行这段代码的过程中,锁定当前对象。
public synchronized void add(String name)
{
num++;
try
{
Thread.sleep(1);
}catch(InterruptedException e){}
System.out.println(name+"你是第"+num+"使用Timer的线程");
}
}
运行结果: