停止/杀死Runnable线程 - 启动新的Runnable线程 - Java

时间:2015-12-13 12:07:38

标签: java multithreading swing selenium-webdriver

我试图从Swing GUI停止可运行的线程。当我点击按钮停止runnable线程时,它会停止它,但之后我无法启动新的runnable线程。

有谁知道这是为什么?任何帮助,将不胜感激。

谢谢

这是我的GUI代码列表

    if(button.getText().equals("Start Scraper")){
        if(validate())
        {
            updateThread.running = true;
            button.setText("Stop Scraper");
            String searchType = comboBox.getSelectedItem().toString();
            String email = emailTextField.getText();
            String password = passwordTextField.getText();
            String searchTerm = searchTermTextField.getText();  
                try{


                    thread = new updateThread(searchTerm, searchType, email, password );
                    thread.start();
                }catch(Exception ex){
                    System.out.println("Something went wrong in the GUI");
                    ex.printStackTrace();
                }
        }else{
            //not valid go again
        }
    }else{
        button.setText("Start Crawler");
        updateThread.running = false;
        updateThread.terminate();

    }
    }
});

这是我的可运行线程类

package guiTool;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.SessionNotFoundException;

import linkedIncrawler.common.Utils;
import linkedin.actions.BaseClass;
import linkedin.actions.LinkedInActions;

public class updateThread extends Thread
{
    private static WebDriver driver;
    public String  searchTerm, searchType, email, password;;
    public volatile static Boolean running = true;
    public updateThread(String searchTerm2, String searchType2, String email2, String password2)
    {
        email = email2;
        password = password2;
        searchTerm = searchTerm2;
        searchType = searchType2;
    }

    public static void terminate() {

        currentThread().interrupt();
        //thread.stop();
        driver.quit();
        running = false;


    }

    @Override
    public void run()
    {
        while(running)
            {
                try {
                    driver = Utils.OpenBrowser("SearchTerms");
                    new BaseClass(driver);
                    LinkedInActions.Execute(searchTerm, searchType, email, password);
                    driver.quit();
                } catch (Exception e) {
                    System.out.println("2nd thread cant run linkedin");
                    e.printStackTrace();
                }
            }
   }

}

2 个答案:

答案 0 :(得分:3)

一旦线程死了,它已经死了......你需要创建一个新线程。关于为什么你不能重新开始一个死线程的重要原因。

而不是扩展Thread,可能会实施Runnable/Callable

答案 1 :(得分:0)

public volatile static Boolean running = true;

这个变量对于所有实例都是通用的,它会停止所有updateThread,当前和未来。删除静态修改器。

相关问题