先看看下面这段简单的代码:class Thread1 extends Thread {    
    private int x = 0;    //非常耗时的工作, 比如计算, 监视...
    public void run() {        
        while (true) {
            x = (x < 100) ? (x + 1) : 0;
        }
    }
}class Thread2 extends Thread {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(i + "Thread 2 is running ...");
        }
    }
}public class Main {
    public static void main(String[] args) {
        Thread1 t1 = new Thread1();
        t1.run();        //t1 没有执行完毕, 就不会执行下面的代码
        System.out.println("Start another thread");
        Thread2 t2 = new Thread2();
        t2.run();
    }
}这算不算多线程程序?t1.run() 做一项非常长时间的工作, 发现 线程 t1 启动后, 如果 t1.run() 没有执行完毕, 就不会执行其他的代码
有什么方法可以一边执行 t1.run(), 一边执行其他的代码 ?

解决方案 »

  1.   

    t1.run();
    t2.run();换成t1.start();
    t2.start();start方法才启动线程
    run只是一个普通的方法 而不是启动线程的方法
      

  2.   

    start方法才启动线程
    run只是一个普通的方法 而不是启动线程的方法同意楼上~
      

  3.   

    -_-#~!t1:
            while (true) {
                x = (x < 100) ? (x + 1) : 0;
            }
    -------------
    死循环,根本轮不到t2;加上sleep,或waite , notify
      

  4.   

    public void start()
    Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. 
    The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
      

  5.   

    public void run()
    If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns. 
    Subclasses of Thread should override this method.
      

  6.   

    不算,只是普通的方法调用,因为你的线程都没有启动阿~
    把main()里的t1.run() t2.run() 换成t1.start() t2.start()
      

  7.   

    上面的都已经说得很清楚了, 线程我也只懂基础, 不过计划接下来看Java Concurrency in practice...
      

  8.   


    前面的说的都没错,用start方法启动后,会产生一个新的Runnable状态的线程,新线程会自动做run里的任务. 如果直接调用run方法,则不会产生新的线程,只是在当前线程里做run任务.
      

  9.   

    哎呀,不好意思,是我写上来的时候一时写错了。
    把 start() 写成了 run();原来问题在于: 在 thread1 启动后, 要很久才会执行下面的代码,
    我很久都看不到显示, 以为不会继续执行下面的代码了。刚果开始学习线程, 多谢各位的指点。qxbnit(蓝灵):
        线程1确实是个死循环, 但是这是其中1个线程, 是会继续执行下面的代码的
    你试下就知道了。
      

  10.   

    必须用start(),才可以启动线程run()。
      

  11.   

    用run()定死!
    用start()t2能得到运行时间,但t1还是死在那里!一种办法:可以两个
    t1:
    while(true){
    //do something1...
    sleep(20);
    }
    t2:
    while(true){
    //do something2...
    sleep(20);
    }
    ========
    t1.start();
    t2.start();