![](/img/trans.png)
[英]Thread communication In simple java program and in Java web application
[英]Simple Communication with a Java Thread
我正在尋找一種非常簡單的方法來與Java中的線程進行通信。 考慮以下示例:
boolean pass=false;
Thread simpleThread=new Thread(){
public void run(){
x=doStuff();
if (x==0) pass=true;
}
}
simpleThread.start();
我只需要知道doStuff()是否返回零即可。 當然,這在Java中是不合法的,但是如何正確實現呢? 看來我需要某種可以由simpleThread編寫並可由主線程讀取的對象。 那件遺失的是什么?
您可能要使用Future<T>
。 與其直接啟動一個新線程, ExecutorService
使用ExecutorService
,並將其傳遞給Callable<T>
。 那將為您返回Future<T>
。
然后,您可以要求Future<T>
在任何時間(從原來的線程)是否已經完成,或者只是阻止,直到它已完成(任選超時)。
您可以使用共享變量手動執行等效操作,但就我個人而言,在有效地在不同線程上計算單個(可能是復雜的)值的情況下, Future
/ Callable
方法更干凈。 如果您需要定期與線程通信(例如,給它更多的工作或查看進度),那么它當然不合適。
一個使用AtomicBoolean的示例:
final AtomicBoolean pass = new AtomicBoolean(false); //making this final means we can access it in the anonymous Thread instance
Thread simpleThread=new Thread(){
public void run(){
x=doStuff();
if (x==0) pass.set(true);
}
}
simpleThread.start();
...
pass.get(); //of course, this could return false simply because the newly spawned thread has not completed execution yet
您需要具有兩個線程可以看到的共享對象。 該對象必須是可修改的。 也就是說,您不能使用原語或基本對象類型,例如String,Integer,Boolean等,因為它們是不可變的。
您還需要了解和使用線程同步。
這是使用列表的示例:
List mylist = new ArrayList();
in-thread
{
synchronized( mylist )
{
mylist.add( _something_ );
}
}
in-another-thread
{
synchronized( mylist )
{
mylist.get( 0 ); // do something with result;
}
}
為了說明@Jon的建議。
ExecutorService executor = ...
Future<Integer> result = executor.submit(new Callable<Integer>() {
public Integer call() {
return doStuff();
}
});
// later.
Integer x = result.get();
boolean pass = x==0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.