安排两个(或更多)任务同时运行(假设核心足够)

时间:2015-01-06 16:48:12

标签: java concurrency

说我想安排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);

1 个答案:

答案 0 :(得分:0)

使用ExecutorService

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