简体   繁体   English

如何启动/停止和监视Java线程?

[英]How to start/stop and monitor a java thread?

I am trying to figure out how to start and stop a serial interface. 我试图弄清楚如何启动和停止串行接口。

class SerialInterface implements Runnable{




 // Stream from file
@Override
public void run(){
    try {
            startInterface();
        } catch (IOException ex) {
            Logger.getLogger(SerialInterface.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main( String StartStop ){
        SerialInterface SerialThread = null;

        if ( StartStop.equals("start")){
        SerialThread = new SerialInterface();
        Thread thread1 = new Thread (SerialThread);
        thread1.start();
        } else {
            SerialThread = null;
        }
    }

 private void startInterface() throws IOException {  //START DOING STUFF TO SERIAL PORT }

This does not work. 这是行不通的。 How do I stop a thread which was started? 如何停止已启动的线程?

thread1.isAlive()将返回一个布尔值,告诉您它是否还存在。

Ok, I think i got this figured out... This main("start") creates a new instance of the thread, then when the main("stop") is called, it creates a new instance of the thread and nulls it out. 好的,我想我已经弄清楚了...这个main(“ start”)创建线程的新实例,然后当main(“ stop”)被调用时,它创建线程的新实例并将其为空出来。 So I need to bring the actual variable creation out of the thread. 因此,我需要将实际的变量创建带出线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM