public class ThreadTest implements Runnable { public static void main(String[] args) { Runnable run = new ThreadTest(); Thread t1 = new Thread(run); Thread t2 = new Thread(run); t1.setName("Thread-01"); t2.setName("Thread-02"); t1.start(); t2.start(); } private int i = 0; public void run() { while (i < 10) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized (this) { if (i >= 10) { break; } i++; System.out .println(Thread.currentThread().getName() + ":i=" + i); } } } }
用synchronized (this)同步
最新推荐文章于 2018-01-23 10:04:00 发布