我希望在完成所有三个线程后执行方法uploadingDone()
。
这些标志大部分时间都正常工作。在极少数情况下,所有三个标志都设置为true,BLOCK1
执行两次。所有三个线程都在不同的数据上执行不同的任务(不会发生并发修改)。
我可以在线程上删除任何本机函数的标志吗?
所有三个线程并行运行(强制性要求)。 BLOCK1应该只被称为 。
private synchronized void uploadingDone(){
if( isItemUploaded && isListUploaded && isStoreUploaded){
uploadingDone = true;
//<BLOCK1>
//TODO move to next screen
}else{
Log.i(TAG, "uploadingDone: Failed");
}
}
private boolean isListUploaded = false, isItemUploaded = false, isStoreUploaded = false, uploadingDone = false;
private class ListUpload extends Thread{
@Override
public void run() {
isListUploaded = true;
Log.i(TAG, "ListUpload Thread started");
if(!uploadingDone)
uploadingDone();
}
}
private class ItemUpload extends Thread{
@Override
public void run() {
Log.i(TAG, "ItemUpload Thread started");
isItemUploaded = true;
if(!uploadingDone)
uploadingDone();
}
}
private class StoreUpload extends Thread{
@Override
public void run() {
Log.i(TAG, "StoreUpload Thread started");
isStoreUploaded = true;
if(!uploadingDone)
uploadingDone();
}
}
private ListUpload listUpload;
private StoreUpload storeUpload;
private ItemUpload itemUpload;
public void startUpload(){
listUpload = new ListUpload();
listUpload.start();
storeUpload = new StoreUpload();
storeUpload.start();
itemUpload = new ItemUpload();
itemUpload.start();
}
谢谢。
答案 0 :(得分:4)
略过标志并添加
listUpload.join();
storeUpload.join();
itemUpload.join();
// <BLOCK1>
在startUpload()的末尾。每次调用join()都会导致调用线程阻塞,直到给定的线程结束。
答案 1 :(得分:0)
我修改了我的来源claesv提到。 我发布了我的结果代码,以显示此Thread.join方法如何简化我的任务。 希望会帮助别人。
private void uploadingDone(){
if( isItemUploaded && isListUploaded && isStoreUploaded){
uploadingDone = true;
//<BLOCK1>
//TODO move to next screen
}else{
Log.i(TAG, "uploadingDone: Failed");
showFailureAlert();
}
}
// These flags are used to VALIDADTION success of uploading process. No need if you no need validation to move screen.
private boolean isListUploaded = false, isItemUploaded = false, isStoreUploaded = false, uploadingDone = false;
private class ListUpload extends Thread{
@Override
public void run() {
isListUploaded = true;
Log.i(TAG, "ListUpload Thread started");
}
}
private class ItemUpload extends Thread{
@Override
public void run() {
Log.i(TAG, "ItemUpload Thread started");
isItemUploaded = true;
}
}
private class StoreUpload extends Thread{
@Override
public void run() {
Log.i(TAG, "StoreUpload Thread started");
isStoreUploaded = true;
}
}
private ListUpload listUpload;
private StoreUpload storeUpload;
private ItemUpload itemUpload;
public void startUpload(){
listUpload = new ListUpload();
listUpload.start();
storeUpload = new StoreUpload();
storeUpload.start();
itemUpload = new ItemUpload();
itemUpload.start();
listUpload.join();
storeUpload.join();
itemUpload.join();
//Here comes the final block to execute after all threads finished
uploadingDone();
}
注意:不要在thread.start()之后放置thread.join() 考虑一下:
t1.start();
t2.start();
t3.start();
t4.start();
t1.join();
t2.join();
t3.join();
t4.join();