7

我使用 timertask 来安排我的 java 程序。现在当 timertask 的 run 方法正在进行时,我想运行两个同时运行并执行不同功能的线程。这是我的代码..请帮助我..

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class timercheck extends TimerTask{
// my first thread
Thread t1 = new Thread(){
     public void run(){
        for(int i = 1;i <= 10;i++)
        {
            System.out.println(i);
        }           
     }
 };

// my second thread
Thread t2 = new Thread(){
     public void run(){
        for(int i = 11;i <= 20;i++)
        {
            System.out.println(i);
        }           
     }
 };

public static void main(String[] args){
      long ONCE_PER_DAY = 1000*60*60*24;

     Calendar calendar = Calendar.getInstance();
     calendar.set(Calendar.HOUR_OF_DAY, 12);
     calendar.set(Calendar.MINUTE, 05);
     calendar.set(Calendar.SECOND, 00);
     Date time = calendar.getTime();

     TimerTask check  = new timercheck();
     Timer timer = new Timer();
     timer.scheduleAtFixedRate(check, time ,ONCE_PER_DAY);
}

@Override    
// run method of timer task
public void run() {
    t1.start();
    t2.start();
}
}
4

2 回答 2

8

我想运行两个同时运行并执行不同功能的线程。

我认为您的线程正在“同一”时间运行。但是由于竞争条件,第一个线程只是在第二个线程之前将其输出排队。您不会看到来自线程 1 的一行,然后是来自线程 2 的 1 行。根据线程调度,您将看到一个然后另一个的块。

如果您将输出量从 10 行增加到(例如)1000 行,您应该看到它们都与隔行输出同时运行。

于 2012-11-07T04:29:11.067 回答
4

如果要同时启动两个线程,请使用 CountDownLatch。

由于您拥有上述代码,因此 t1 在 t2 之前有资格运行(Runnable)。因此,由 Java 调度程序决定是混合 t1 和 t2 还是先完成 t1 然后完成 t2。但是,如果您希望 t1 和 t2 都等待提示开始执行,CountDownLatch 可以帮助您。

public class timercheck extends TimerTask{

private final CountDownLatch countDownLatch  = new CountDownLatch(1);

    // my first thread
    Thread t1 = new Thread(){
         public void run(){

            countDownLatch.await();  

            for(int i = 1;i <= 10;i++)
            {
                System.out.println(i);
            }           
         }
     };

    // my second thread
    Thread t2 = new Thread(){

         public void run(){

            countDownLatch.await();

            for(int i = 11;i <= 20;i++)
            {
                System.out.println(i);
            }           
         }
     };

        public void run() {
            t1.start();
            t2.start();
            countDownLatch.countDown();
        }

有关 CountDownLatch、Semaphore 和 CyclicBarrier 的更多信息,请阅读这篇文章。

于 2012-11-07T04:48:25.783 回答