java中的简单多线程方法。它是否正确?

时间:2015-06-17 11:04:16

标签: java multithreading

我为java中的测试自动化构建了一个多线程进程。该过程必须执行允许执行第二个命令的第一个命令。代码有效,但我知道有更好的方法(5个中的1个将失败,因为第二个命令在第一个命令之前执行)。有人可以看看它并帮助我一点吗?我上次在大学时已经建立了多线程。

public static void addRestfulAPIToSupport() throws Exception
    {   
    try{
    //This is the point where i have to use multithread
    //add slave - multithread part
            fifth obj5 = new fifth();
            obj5.start();

            sixth obj6 = new sixth();
            obj6.start();

            Thread.sleep(60000);// i leave to sleep it for 1 min
            //code continues here

    }catch(Exception e)
        log.log(e.getMessage());
    }

}
//class fifth and sixth for my restful api test - adding slave 1 to the cluster
class fifth extends Thread
{
    public static WebDriver driver;

    public void runMultiThread3()
    {
        String slave1 = "172.xx.x.xx";
        String shared = "172.xx.x.xxx";
        String user = "xxx";
        String pass = "xxxxxx";
        log.log("Thread join cluster for slave 1 of ip " + slave1);
        driver = new FirefoxDriver();         
        try
        {

            for (int i = 0; i < 1; i++)
            {
                driver.get("https://" + user + ":" + pass + "@" + slave1 + "/access/cluster/joincluster");
                Thread.sleep(1000);
                driver.close();
            }

        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
        try
        {
            Thread.sleep(100);
        }
        catch (InterruptedException i)
        {
            Logger.getLogger(sixth.class.getName()).log(Level.SEVERE, null, i);
        }

    }

    public void run()
    {
        runMultiThread3();
    }
}

class sixth extends Thread
{
    public static WebDriver driver;

    public void runMultiThread3()
    {
        String shared = "172.xx.x.xxx";
        String slave1 = "172.xx.x.xx";
        String user = "xxx";
        String pass = "xxxxxx";
        log.log("Thread add node to the cluster for slave 1 of ip " + slave1);
        driver = new FirefoxDriver();       
        try
        {
            driver.get("https://" + user + ":" + pass + "@" + shared + "/access/cluster/addnode?address=" + slave1);


            for (int i = 0; i < 1; i++)
            {
                driver.get("https://" + user + ":" + pass + "@" + shared + "/access/cluster/addnode?address=" + slave1);
                Thread.sleep(1000);
                driver.close();
            }

        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
        try
        {
            Thread.sleep(100);
        }
        catch (InterruptedException i)
        {
            Logger.getLogger(fifth.class.getName()).log(Level.SEVERE, null, i);
        }

    }

    public void run()
    {
        runMultiThread3();
    }

}

0 个答案:

没有答案