本文介绍了为什么不在构造函数中启动一个线程?如何终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何在Java中使用线程。我写了一个实现Runnable的类,它可以并发运行到另一个线程。主线程处理侦听串口,其中第二个线程将处理将数据发送到同一端口。

I am learning how to use threads in Java. And I wrote a class that implements Runnable to run concurrently to another thread. The main thread handles listening to the serial port where as the second thread will handle sending data to that same port.

public class MyNewThread implements Runnable {
    Thread t;

    MyNewThread() {
        t = new Thread (this, "Data Thread");
        t.start();
    }

    public void run()  {
        // New Thread code here
    }

第一个线程会像这样开始第二个:

There first thread starts the second like this:

public class Main {
    public static void main(String[] args) throws Exception{
        new MyNewThread();
        // First thread code there
    }
}

这个但是我的编译器标记了一个警告说:在构造函数中启动一个新线程是危险的。这是为什么?

This works but my complier flags a warning saying: It is dangerous to start a new thread in the constructor. Why is this?

这个问题的第二部分是:如果我在一个线程中运行一个循环(串口侦听线程),我输入一个退出命令在我的第二个帖子中。如何获得第一个终止线程?谢谢。

The second part to this question is: how if I have a loop running in one thread (the serial port listen thread) and I type an exit command in my second thread. How do I get the first thread to terminate? Thanks.

推荐答案

第一个问题:在构造函数中启动一个传递的线程转义。这意味着您实际上是在完全构造对象之前给出了对象的引用。线程将在构造函数完成之前启动。这可能导致各种奇怪的行为。

To your first question: Starting a thread in a constructor passing in this escapes this. That means that you are actually giving out a reference to your object before it is fully constructed. The thread will start before your constructor finishes. This can result in all kinds of weird behaviors.

对于你的第二个问题:没有可接受的方法强制另一个线程在Java中停止,所以你会使用一个变量哪个线程会检查它是否应该停止。另一个线程将其设置为指示第一个线程将停止。变量必须是volatile或所有访问同步以确保正确发布。下面是一些类似于你想要的代码。

To your second question: There is no acceptable way to force another thread to stop in Java, so you would use a variable which the thread would check to know whether or not it should stop. The other thread would set it to indicate that the first thread would stop. The variable has to be volatile or all accesses synchronized to ensure proper publication. Here is some code which would be something like what you want.

public class MyNewThread implements Runnable {

    private final Thread t;
    private volatile boolean shouldStop = false;

    MyNewThread() {
        t = new Thread (this, "Data Thread");
    }

    public void start() {
        t.start();
    }

    public void stop() {
         shouldStop = true;
    }

    public void run()  {
         while(!shouldStop)
         {
             // do stuff
         }
    }
}

无论想创建什么并启动线程都可以:

Whatever wants to create and start the thread would do:

MyNewThread thread = new MyNewThread();
thread.start();

无论什么想要阻止该线程:

Whatever wants to stop the thread would do:

thread.stop();

这篇关于为什么不在构造函数中启动一个线程?如何终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 05:12