Java Thread - 如何避免并發(fā)執(zhí)行一個耗時的任務(wù)而不阻塞...
我們想知道如何避免并發(fā)執(zhí)行一個耗時的任務(wù)而不阻塞。...
public class Main {
public static void main(String[] args) throws Exception {
Thread previousThread = null;
for (int i = 0; i < 20; i++) {
JobRunnable job = new JobRunnable(i, previousThread);
Thread thread = new Thread(job, "T-" + i);
thread.start();
previousThread = thread;
}
if (previousThread != null) {
previousThread.join();
}
System.out.println("Program done.");
}
}
class JobRunnable implements Runnable {
final int _lineIdx;
final Thread t;
public JobRunnable(int lineIdx, Thread threadToWaitForBeforePrinting) {
_lineIdx = lineIdx;
t = threadToWaitForBeforePrinting;
}
public void run() {
try {
String currentThreadName = Thread.currentThread().getName();
if (t != null) {
t.join();
}
Thread.sleep(3000);
System.out.println("RESULT: " + _lineIdx + " " + " (Printed on Thread "
+ currentThreadName + ")");
} catch (Exception e) {
Thread.currentThread().interrupt();
}
}
}