线程的同步

来源:互联网 发布:linux 访问url 命令 编辑:程序博客网 时间:2024/06/03 22:55
线程的同步:
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,这样写起来简单点
原创粉丝点击