Java线程完成状态

时间:2017-05-23 15:05:48

标签: java multithreading thread-safety threadpool

我有2个帖子t1t2,每个人都执行单独的任务。

我想在线程t1中完成60%任务后启动线程t2。

有谁知道我怎么能实现它?

2 个答案:

答案 0 :(得分:0)

@Test
public void test() throws InterruptedException{
    Thread t = new Thread( new Task1() );

    t.start();

    t.join(0);

    //keep in mind that t2 can still be running at this point
    System.out.println("done running task1.");
}

public static class Task1 implements Runnable{

    public void run(){
        //Smimulate some long running job. In your case you need to have your own logic of checking if t1 is 60% done.
        //In this case we just wait 0.5 seconds for each 10% of work done
        for (int i = 0; i < 10; i++){

           try {  Thread.sleep(500); } 
           catch (InterruptedException e) { throw new RuntimeException(e); }   

           int percentComplete = i*10;

           System.out.println("Completed " + percentComplete + "%.");

           if (percentComplete == 60){
               new Thread( new Task2() ).start();  //this how to start t2 when we are 60% complete 
           }
        }            
    }
}

public static class Task2 implements Runnable{

    @Override
    public void run() {
        //simulate t2 task that will run for 5 seconds. 

        System.out.println("task2 started.");

        try {  Thread.sleep(5000); } 
        catch (InterruptedException e) { throw new RuntimeException(e); } 

        System.out.println("task2 is done.");
    }

}

答案 1 :(得分:0)

T1可以知道什么时候完成了60%吗?如果是这样,那么为什么不让它在那时开始T2?

Thread t2 = null;

class T2task implements Runnable {
    ...
}

class T1task implements Runnable {
    @Override
    public void run() {
        while (isNotFinished(...)) {
            if (isAtLeast60PercentDone(...) && t2 != null) {
                t2 = new Thread(new T2task(...));
                t2.start();
            }
            doSomeMoreWork(...);
        }
    }
}