简体   繁体   中英

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. So I need to bring the actual variable creation out of the thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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