欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

线程同步

程序员文章站 2022-04-17 18:29:58
...


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());

}
}
相关标签: thread