第九章 Java多线程机制 05_线程同步_五

第九章 Java多线程机制 05_线程同步_5

鱼欲遇雨:每日都学习一点,持之以恒,天道酬勤!不能用电脑时,提前补上!(2012.9.3)


考虑这个对象的所有相关的方法是否加同步synchronized

解决上个java面试的问题,就是把m2也加上synchronized的!

// TT.java

public class TT implements Runnable {
	private int b = 100;

	public synchronized void m1() throws Exception {
		b = 1000;
		Thread.sleep(5000);
		System.out.println("b = " + b);
	}

	public synchronized void m2() throws Exception {
		Thread.sleep(2500);
		System.out.println(b);
		b = 2000;
	}

	public void run() {
		try
		{
			m1();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public static void main(String args[]) throws Exception {
		TT tt = new TT();
		Thread t = new Thread(tt);
		t.start();

		//Thread.sleep(1000);
		tt.m2();
		System.out.println(tt.b);
	}

}