说我想安排2个任务同时运行。 我该怎么做?
这是我尝试过的,但它看起来只是近似
class MyTask extends TimerTask {
String name;
MyTask(String n) {
name = n;
}
@Override
public void run() {
System.err.println("from task " + name);
}
}
// now use the tasks
MyTask first = new MyTask("first");
MyTask second = new MyTask("second");
Timer t1 = new Timer();
Timer t2 = new Timer();
t1.schedule(first, 2); // wait "some" time?
t2.schedule(second, 0);
答案 0 :(得分:0)
ExecutorService es = Executors.newFixedThreadPool(2); // 2 threads
Runnable first = new MyTask("first");
Runnable second = new MyTask("second");
es.submit(first); // first starts running
es.submit(second); // second starts running in parallel