从方法更改参数

时间:2015-04-24 08:16:10

标签: java multithreading parameters

我是java的编程新手,我希望我选择了正确的标题。 首先我的代码:

public class main 
{

    public static void main(String args[])
    {

        SysOutSleep sos = new SysOutSleep("Test", 450, 3 );//set the value

        Thread t = new Thread(sos); 

        t.start(); 

        //here i want to change the parameters from sos 
        //they should be something like that ("Test2", 390, 1)

        //and after that i start the thread again with the new parameters

        t.start();
    }

}

所以我怎么能改变它们,提前谢谢你们:)

2 个答案:

答案 0 :(得分:3)

你不能两次启动相同的Thread isntance,这意味着你必须创建一个新的线程:

SysOutSleep sos = new SysOutSleep("Test", 450, 3);
Thread t = new Thread(sos); 
t.start(); 

sos = new SysOutSleep("Test2", 390, 1);
t = new Thread(sos);
t.start();

答案 1 :(得分:1)

如果您只想在同一方法中使用其他参数,则只需更改

中的值即可
SysOutSleep sos = new SysOutSleep("Test", 450, 3 );//set the value

SysOutSleep sos = new SysOutSleep("Test2", 390, 1 );

如果你想要同时使用两种情况执行这两种方法并使用两种不同的线程,那么你将不得不创建两个线程。

SysOutSleep sos1 = new SysOutSleep("Test", 450, 3); // create object of SysOutSleep class and invoke constructor of SysOutSleep class with the given parameters
Thread t1 = new Thread(sos); // create thread for sos1 object and starts thread
t1.start();  // after start thread it will run the run method of thread

sos2 = new SysOutSleep("Test2", 390, 1);
Thread t2 = new Thread(sos);
t2.start();