public class Timer {
private static int num = 0;
public synchronized void add(String name) { //在执行这个方法过程中,当前对象被锁定
num ++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name + " 你是第"+num + "个使用Timer的线程");
}
}
public class TestSync implements Runnable{
Timer timer = new Timer();
public static void main(String[] args) {
TestSync testSync = new TestSync();
Thread t1 = new Thread(testSync);
Thread t2 = new Thread(testSync);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run() {
timer.add(Thread.currentThread().getName());
}
}
线程同步
最新推荐文章于 2025-04-21 07:00:00 发布