【问题标题】:start() is not starting a threadstart() 没有启动线程
【发布时间】:2018-03-10 17:34:24
【问题描述】:

我在下面编写了示例代码来测试线程的行为。但是 main 没有启动线程 test1 执行,请让我知道这段代码有什么问题

class test1 implements Runnable
{

    Thread t ; 

    test1(String Name)
    {
        t = new Thread(Name);
        t.start();
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("Entered test1 run");
    }

}


public class SampleThread{

    public static void main(String[] args)  {
        Thread r = Thread.currentThread();
        System.out.println(r.getName()+" "+r.getPriority());
        r.setName("MainThread");
        r.setPriority(8);
        test1 t1 = new test1("test1");
        System.out.println("calling threads");
        try
        {
            t1.t.join();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

【问题讨论】:

  • 你永远不会将你的 Runnable 放入一个线程中,因此它的 run 方法永远不会运行。这是基本线程,建议您在 Google 上学习有关 Java 线程入门的教程。

标签: java multithreading


【解决方案1】:

t = new Thread(Name); 更改为 t = new Thread(this, Name);(在 test1 中)将使您的代码正常工作。

但是您的代码仍然很混乱。您可以通过子类化 Thread 或实现 Runnable 并将 runnable 传递给线程来创建 java 线程,并且您似乎试图同时(错误地)执行这两项操作。

我建议您查找有关线程的指南,例如 https://www.tutorialspoint.com/java/java_multithreading.htm

【讨论】:

  • 感谢您的回复,更改 t = new Thread(this);已经工作了:)
  • 对象构造函数绝不能允许其this 指针被另一个线程看到。这样做可以让其他线程看到处于不一致状态的对象。
猜你喜欢
  • 2018-03-17
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-27
相关资源
最近更新 更多