public String name;
}
public static MyObj obj = new MyObj();
/**
* @param args
*/
public static void main(String[] args) throws Throwable {
new TestMain().myTest();
}
public void myTest() throws Throwable{
Test1 test1 = new Test1();
Test2 test2 = new Test2();
Thread t1 = new Thread(test1);
Thread t2 = new Thread(test2);
t1.start();
Thread.sleep(1000);//啟動(dòng)線程1,然后主線程睡眠1秒鐘,再啟動(dòng)2
t2.start();
}
}
@Override
public void run() {
synchronized (TestMain.obj) {//占有對(duì)象鎖
try {
TestMain.obj.name="1";
System.out.println(TestMain.obj.name); //打印出1
TestMain.obj.wait(); //釋放對(duì)TestMain.obj對(duì)象的鎖,同時(shí)當(dāng)前線程立即卡住,陷入等待
System.out.println(TestMain.obj.name);//只有線程再次搶到TestMain.obj的鎖后,才會(huì)運(yùn)行
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void run() {
synchronized (TestMain.obj) { //當(dāng)線程1釋放這個(gè)對(duì)象的鎖時(shí),本線程立即得到
TestMain.obj.name = "2"; //改值
TestMain.obj.notify();//通知占用了TestMain.obj且當(dāng)前是等待的線程(線程1)可以繼續(xù),但是必須等到本synchronized塊執(zhí)行完畢。
TestMain.obj.name = "3";
TestMain.obj.name = "4";
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
TestMain.obj.name = "7";//執(zhí)行完畢,此時(shí)線程1被喚醒,會(huì)打印出7
}
}
}
posted @ 2013-04-27 15:23 landor 閱讀(356) | 評(píng)論 (0) | 編輯 收藏