[英]run two thread at the same time in java
我已經使用 timertask 來安排我的 java 程序。 現在,當 timertask 的運行方法正在運行時,我想運行兩個同時運行的線程並執行不同的功能。 這是我的代碼..請幫助我..
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();
}
}
我想運行兩個同時運行的線程並執行不同的功能。
我認為您的線程在“同一”時間運行。 但是由於競爭條件,第一個線程只是在第二個線程之前排隊它的輸出。 您不會看到來自線程 1 的一行和來自線程 2 的 1 行。 根據線程調度,您將看到一個塊然后另一個塊。
如果將輸出量從 10 行增加到(例如)1000 行,您應該會看到它們都以隔行掃描輸出同時運行。
如果您想同時啟動兩個線程,請使用 CountDownLatch。
由於您具有上述代碼,因此 t1 在 t2 之前有資格運行(可運行)。 所以由 Java Scheduler 來選擇是混合 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 的更多信息,請閱讀這篇文章。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.