【问题标题】:Why arent the threads running concurrently?为什么线程不能同时运行?
【发布时间】:2014-06-17 18:58:29
【问题描述】:

我正在运行一个非常简单的多线程程序

主程序

package javathread;


public class JavaThread {


    public static void main(String[] args) 
    {

        JThread t1 = new JThread(10,1);
        JThread t2 = new JThread(10,2);

        t1.run();
        t2.run();

    }
}

JThread.java

package javathread;

import java.util.Random;

public class JThread implements Runnable
{
    JThread(int limit , int threadno)
    {
        t = new Thread();
        this.limit = limit;
        this.threadno = threadno;

    }

    public void run()
    {
        Random generator = new Random();

        for (int i=0;i<this.limit;i++)
        {
            int num = generator.nextInt();

            System.out.println("Thread " + threadno + " : The num is " + num   );
            try
            {
            Thread.sleep(100);
            }
            catch (InterruptedException ie)
            {

            }
        }

    }




    Thread t;
    private int limit;
    int threadno;
}

我希望两个线程同时/并行运行,类似于这张图片

相反,我得到的是线程 1 先运行然后线程 2 运行的地方

有人可以向我解释为什么会这样吗?

如何让线程同时运行?

【问题讨论】:

  • 老兄,首先阅读线程基础知识。线程生命周期从调用 Thread 对象的 start 方法开始,而不是从运行开始。 run 由线程在内部调用以同时执行基于“运行”的任务。
  • run 公开以及将Thread 设为非最终版本肯定是Java API 中最糟糕的设计决策,本可以避免的大量混乱。

标签: java multithreading concurrency parallel-processing


【解决方案1】:

因为您调用了t1.run()t2.run() 而不是t1.start()t2.start()

如果你调用run,它只是一个普通的方法调用。它在完成之前不会返回,就像任何方法一样。它不会同时运行任何东西。 run 绝对没有什么特别之处。

start 是您调用以启动另一个线程并在新线程中调用run 的“魔术”方法。 (顺便说一下,调用start 也是一个普通的方法调用。是start 中的代码发挥了作用)

【讨论】:

  • 他的问题更基本:JThread 实现了 Runnable,它不是一个实际的线程(我认为他试图通过在 JThread 的 Ctor 中创建一个实际的线程来使用它)。
  • 我也这么认为。我也花了一段时间才注意到:P
【解决方案2】:

因为你应该 start() 线程, run() 它。

【讨论】:

    【解决方案3】:

    你不在线程上运行任何东西,你只是运行 Runnable(你的 JThread 不是一个线程,它只是一个不可运行的)。 要在线程上运行,您需要执行以下操作:

    new Thread(myRunnable).start();
    

    在 Runnable 中创建线程什么都不做(就像您在 JThread 构造函数中所做的那样)。

    【讨论】:

      【解决方案4】:

      请转至Life Cycle of a Thread

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-11
        • 2017-03-27
        相关资源
        最近更新 更多