线程的同步:
当然,也可以在void add前加synchronized,这样写起来简单点
public class TestSync implements Runnable{
Timer timer = new Timer();
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();
}
public void run() {
timer.add(Thread.currentThread().getName());
}
}
class Timer{
private static int num = 0;
public void add(String name){
//如果不加synchronized,那么打印出的都是“你是第2个访问的人”
synchronized (this) {
num ++;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + ": 你是第" + num + "个访问的人");
}
}
}
当然,也可以在void add前加synchronized,这样写起来简单点