线程同步

来源:互联网 发布:手机计算软件 编辑:程序博客网 时间:2024/06/07 04:54
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 synchronized void add(String n) {//public void add(String n) {//synchronized(this){num++;try{Thread.sleep(1);} catch (InterruptedException e){}System.out.println(n + "你是第" + num + "个");}//}}
/*synchronized的意思是锁定线程,不允许其他线程打断*/
                                             
0 0
原创粉丝点击