[英]Calling method of blocked thread
我才剛剛開始學習Java中的多線程,並且仍在弄清楚一些事情。 首先,擴展Thread
的類是否可以具有與其關聯的其他實例方法,這些實例方法可以在其執行期間被調用-如果是的話,它可以在執行期間更改線程的狀態嗎? 其次,如果此類在等待信號量時被阻塞,是否仍可以調用其實例方法? 就像運行這兩個線程一樣:
Thread1 t;
public class Thread1 extends Thread {
private int num;
public run() {
sem.acquire(); // here it blocks waiting for another thread
//to call its setInt function and release it
System.out.println("num is " + num);
}
public void setInt(int i) {
num = i;
}
}
public class Thread2 extends Thread {
public run() {
t.setInt(5);
sem.release();
}
}
這里有些混亂。
為了演示您在尋找什么,這是我測試過的代碼示例:
package test2;
import java.util.concurrent.Semaphore;
public class mainclass {
static Thread1 t;
static Semaphore sem;
static Semaphore sem_protect;
public synchronized static void main (String[] args) {
sem = new Semaphore(0);
sem_protect = new Semaphore(1);
t = new Thread1();
Thread1 th1 = new Thread1();
th1.start();
Thread2 th2 = new Thread2();
th2.start();
try {
synchronized (th2){
th2.wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("The end !");
}
public static class Thread1 extends Thread {
private int num;
public void run() {
try {
sem.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // here it blocks waiting for another thread
//to call its setInt function and release it
try {
sem_protect.acquire();
System.out.println("num is " + num);
sem_protect.release();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void setInt(int i) {
try {
sem_protect.acquire();
this.num = i;
sem_protect.release();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("value of num is: "+num);
}
}
public static class Thread2 extends Thread {
public void run() {
t.setInt(5);
sem.release();
}
}
}
這是執行此代碼的結果:
value of num is: 5
The end !
num is 0
通過此結果,您可以看到仍然可以從Thread2訪問類thread1的方法。 這意味着您訪問類實例的方法,沒有用於線程的方法。 (這是您第一個問題的答案)
第一個線程的狀態不會被第二個線程更改,第一個線程的num
仍為0,這些線程各自具有各自的上下文。
即使我們用另一個信號量保護對num
的訪問,我們對於兩個線程也沒有相同的num
值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.