按我的理解,當(dāng)一個(gè)線程需要獲取的鎖被另一個(gè)線程占用時(shí),將進(jìn)入阻塞態(tài)。但實(shí)際好像不是這樣的,下面是我的代碼。在run方法中會(huì)調(diào)用MyBlock的isBlocked方法,該方法添加了synchronized限定。在main方法中創(chuàng)建兩個(gè)線程:t1和t2,t1運(yùn)行后,由于isBlocked方法運(yùn)行需要一定時(shí)間,t2應(yīng)該進(jìn)入阻塞態(tài)。但我調(diào)用getState方法得到的是Runnable,不是Blocked。這是為啥呢? public class TestThread implements Runnable {
private String mThreadName = null;
private MyLock mLock = null;
public TestThread(String name, MyLock l){
mThreadName = name;
mLock = l;
}
@Override
public void run() {
// TODO Auto-generated method stub
subTask();
}
private void subTask()
{
System.out.println(mThreadName + "START!");
mLock.isLocked();
System.out.println(mThreadName + "END!");
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyLock lock = new MyLock();
TestThread r1 = new TestThread("A", lock);
Thread t1 = new Thread(r1);
t1.start();
TestThread r2 = new TestThread("B", lock);
Thread t2 = new Thread(r2);
t2.start();
System.out.println(t2.getState());
//t2.interrupt();
System.out.println(t2.getState());
System.out.println("MAIN END!");
}
public static class MyLock{
private ReentrantLock mLock = new ReentrantLock();
public synchronized void isLocked(){
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
for (int i = 0; i < 10000; i ++){
System.out.print("," + i);
}
System.out.println("#############################");
}
}
}
5 回答

茅侃侃
TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超21個(gè)贊
private ReentrantLock mLock = new ReentrantLock();
還可以用mLock通過(guò)trylock和lock去在臨界區(qū)枷鎖測(cè)試。

白板的微信
TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
package iteye;
public class TestThread implements Runnable {
private final String mThreadName;
private final MyLock mLock;
public TestThread(String name, MyLock l) { mThreadName = name; mLock = l; } public void run() { System.out.println(mThreadName + " START!"); mLock.lock(); System.out.println(mThreadName + " END!"); } /** * @param args */ public static void main(String[] args) { MyLock lock = new MyLock(); TestThread r1 = new TestThread("A", lock); Thread t1 = new Thread(r1); t1.start(); // 確保t1先進(jìn)入run方法 try { Thread.sleep(1000); } catch (InterruptedException e) { } TestThread r2 = new TestThread("B", lock); Thread t2 = new Thread(r2); t2.start(); // 確保t2進(jìn)入run方法 try { Thread.sleep(1000); } catch (InterruptedException e) { } // 只有t1正在執(zhí)行l(wèi)ock方法中,而t2也進(jìn)入run方法等待執(zhí)行l(wèi)ock方法時(shí),t2的狀態(tài)才是BLOCKED System.out.println(t2.getState()); System.out.println("MAIN END!"); } public static class MyLock { public synchronized void lock() { try { Thread.sleep(7000);//模擬線程的執(zhí)行時(shí)間比較長(zhǎng) } catch (InterruptedException e) { e.printStackTrace(); } } }
}
添加回答
舉報(bào)
0/150
提交
取消