在java中同时运行两个线程 [英] run two thread at the same time in java

查看:516
本文介绍了在java中同时运行两个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have used timertask to schedule my java program. now when the run method of timertask is in process, i want to run two threads which run at the same time and do different functions. here is my code.. please help me..

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


推荐答案

我认为您的线程 在相同时间运行。但由于竞争条件,第一个线程只是在第二个线程之前将其输出排队。你不会从thread-1看到一行,然后从thread-2看到1行。您将看到一个块然后另一个块,具体取决于线程安排。

I think your threads are running at the "same" time. But because of race conditions, the first thread is just queueing its output before the 2nd. You will not see one line from thread-1 and then 1 line from thread-2. You will see blocks from one and then the other depending on the thread scheduling.

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

If you increase the amount of output from 10 lines to (for example) 1000, you should see that they are both running concurrently with interlaced output.

这篇关于在java中同时运行两个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆