如何讓一個線程不斷跑起來,并且在取到值的時候能返回值而線程能繼續跑呢?
我們都知道可以用callable接口獲得線程的返回值,或者觸發事件監聽來操作返回值,下面我將介紹另一種方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public abstract class test implements runnable { public string a; //開啟線程 public void run() { while ( true ) { //此處寫該方法的邏輯代碼 //listen()方法操作取得值a listen(a); } } //定義一個抽象方法listen() public abstract void listen(string a); } |
這樣,線程取到值將存放在抽象方法listen()里,并且線程也將一直跑起來而不會停止。
當我們需要用到這個值時,只需要重寫listen()方法就可以啦。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class main { public static void main(string[] args) { thread thread = new thread( new test() { @override public void listen(string a) { // todo auto-generated method stub } }); thread.start(); } } |
以上就是本知識點的全部內容,感謝大家對服務器之家的支持。