【问题标题】:Java Thread completion statusJava 线程完成状态
【发布时间】:2017-10-23 15:04:39
【问题描述】:

我有 2 个线程 t1t2,每个线程执行单独的任务。

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

有人知道我该如何实现吗?

【问题讨论】:

  • 我们怎么知道它已经完成了 60%?您没有提供相关代码,我们无法提供帮助。
  • 这就是我的问题..java线程中是否有任何内置库要查找?
  • 听起来你在要求一个函数 h(A) 其中 A 是一个 activation record 用于一些任意的其他函数,a(...);并且您希望 h(A) 计算在对 a(...) 的调用返回之前将经过多少时间。没关系,激活记录不是您可以在 Java 中反映的对象。更大的障碍是你可以使用 h(A) 来解决halting problem.
  • 您必须能够将任务分解为可衡量的子任务。由于您尚未发布任何代码,因此我们无法为您提供帮助。

标签: java multithreading thread-safety threadpool


【解决方案1】:
@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.");
    }

}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2011-06-09
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      相关资源
      最近更新 更多