简体   繁体   English

如何使用新配置停止和启动线程?

[英]How to stop and start a Thread with new configuration?

My program is whenever i start my AccelSender program, it sends epnId to my server machine to request host for that particular epnId. 每当我启动我的AccelSender程序时,我的程序就会将epnId发送到我的服务器计算机,以请求该特定epnId的主机。 When the server returns hostName, it starts two Runnable Thread class called new DataTransmitter(hostName,epnId) and new JMSConnection() . 服务器返回hostName时,它将启动两个名为new DataTransmitter(hostName,epnId)和new JMSConnection() Runnable Thread类。

What i am trying to do is whenever my reStart(String hostName) is invoked i want to stop the new DataTransmitter(hostName,epnId) thread and start it with setting new hostName. 我想做的是每当调用reStart(String hostName)我想停止new DataTransmitter(hostName,epnId)线程并通过设置新的hostName来启动它时。

Here is my code: 这是我的代码:

public class AccelSender {

        private Socket kkSocket = null;
        private PrintWriter out = null;
        private BufferedReader in = null;

        private static final String epnId = "EPN1";

        public AccelSender(){
        }

        public void requestHost(){

            try{
                Socket hostSocket = new Socket("10.3.2.227",1121);
                PrintWriter out = new PrintWriter(hostSocket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(hostSocket.getInputStream()));
                out.println(epnId);
                    while(true){
                        String hostName = in.readLine();
                        DataTransmitter dt = new DataTransmitter(hostName,epnId);
                        JMSConnection jms = new JMSConnection();
                        new Thread(dt).start();
                        new Thread(jms).start();
                    }
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }

    public void reStart(String hostName){
    //Here i want to STOP the DataTransmitter Thread and,
 START with new hostName
        }

    }

Code for Runnable class: 可运行类的代码:

public class DataTransmitter implements Runnable {

    private Socket kkSocket = null;
    private PrintWriter out = null;
    private BufferedReader in = null;

    private int port = 2508, fileCount = 0, arrivalRate = 500;
    private String hostName = null, data = null, filename = null;
    private boolean resetSender = false;
    private static String epnId = null;
    File folder = new File(System.getProperty("user.dir")+"/input_data");
    File[] listOfFiles = folder.listFiles();

    public DataTransmitter(){
    }


    public DataTransmitter(String hostName, String epnId){

        this.hostName = hostName;
        this.epnId = epnId;
        establishHostConnection();
    }

    public void establishHostConnection(){

        try {
            kkSocket = new Socket(hostName, port);
            out = new PrintWriter(kkSocket.getOutputStream(), true);
            in = new BufferedReader(new 
InputStreamReader(kkSocket.getInputStream()));
            resetSender = true;
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: thinklatch.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: 
thinklatch.");
            System.exit(1);
        }
    }

    public void close() throws IOException{

        kkSocket.close();
        out.close();
        in.close();
    }

    public void run(){

        System.out.println("Entering Data Transmitter");

        try{
            while (fileCount <= 1) {


                for (int i = 0; i < listOfFiles.length; i++) {
                    if (listOfFiles[i].isFile()) {
                        System.out.println("File " + 
listOfFiles[i].getName());
                        filename = System.getProperty("user.dir") + 
"/input_data/" + listOfFiles[i].getName();

                        BufferedReader bf = new BufferedReader(new 
FileReader(filename));
                        System.out.println("Fetching input from : " + 
filename);

                        while((data=bf.readLine())!=null){
                            String str = 
this.hostName+","+this.epnId+","+arrivalRate+","+data;
                            out.println(str);
                            try{
                                TimeUnit.MILLISECONDS.sleep(2);
                            }catch(Exception e){
                            }
                        }
                    }
                }
                     fileCount++;
            }
        }catch(FileNotFoundException fnfe){
            System.err.println("E"+fnfe);
        }catch(IOException ioe){
            System.err.println("E"+ioe);
        }
            out.close();
    }
}

Any advice on restarting the thread for this case is appreciable. 在这种情况下,有关重启线程的任何建议都是可取的。 Thanks in advance .... 提前致谢 ....

A thread can't actually be "restarted" once the run method has finished executing. run方法完成执行后,实际上无法“重新启动”线程。 You have two options basically: 您基本上有两个选择:

  1. Introduce a loop that causes the thread to be suspended (eg call a wait ) when a condition is met. 引入一个循环,当满足条件时,该循环将导致线程挂起(例如,调用wait )。 That way you can "pause" the thread, change the hostname and then signal it to resume. 这样,您可以“暂停”线程,更改主机名,然后发出信号以使其恢复。
  2. Cause the thread to finish its code, discard it and then start a new thread with the same Runnable object. 使线程完成其代码,将其丢弃,然后使用相同的Runnable对象启动一个新线程。

Edit : So what you can do in the restart method is to call to close method on the dt object. 编辑 :因此,您可以在restart方法中执行的操作是在dt对象上调用close方法。 This will close the sockets and cause an IOException that will make the thread exit its run method. 这将关闭套接字并导致IOException ,该IOException将使线程退出其run方法。 After that you can just start a new thread: 之后,您可以启动一个新线程:

dt = new DataTransmitter(hostName,epnId);
new Thread(dt).start();

Use Thread.currentThread().isInterrupted() and Thread.interrupt() 使用Thread.currentThread()。isInterrupted()和Thread.interrupt()

See this link : 看到这个链接:

http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

Thread once stopped can't be restarted . Thread一旦停止can't be restarted

- Once the thread of Execution associated with the Thread Class Instance finishes its run() method, it moves into the Dead State , or Thread Pool if implemented. -一旦与线程类实例相关联的执行线程完成其run()方法,它将进入Dead StateThread Pool如果已实现)。 The Thread Class Instance which was associated with the thread of Execution Permanently looses its Threadness. 与执行线程关联的线程类实例永久失去其线程性。

- You can better use the wait() and notify() mechanism, and can also use await() and signal() mechanism from java.util.concurrent package, to suspend and resume the thread. -您可以更好地使用wait()notify()机制,还可以使用java.util.concurrent包中的await()signal()机制来挂起和恢复线程。

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

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