java怎么处理耗时久的任务_Java Thread - 如何避免并发执行一个耗时的任务而不阻塞......

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();

}

}

}

你可能感兴趣的:(java怎么处理耗时久的任务)