我对多线程还不熟悉,在练习时写了以下代码。每次调用createThread方法时,我希望它创建一个新的线程。然而,使用下面给出的代码时,每次调用createThread方法时,我都会得到相同的线程一遍又一遍地运行。使用相同的对象是否可以创建新线程?显然不行,但只是想确认我是否存在不知道的方法。
public class ThreadStartRunnable implements Runnable {
private Thread t;
/*
ThreadStartRunnable(String name) {
t = new Thread(this, name);
t.start();
}
*/
private Thread createThread(String name){
t = new Thread(this,name);
t.start();
return t;
}
/**
* @Override run
*
*/
public void run() {
for(int i=0;i<=5;i++)
{
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("The current Thread is " + t.getName() + " and thread ID is " + t.getId());
}
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t = Thread.currentThread();
//new ThreadStartRunnable("User 1");
//new ThreadStartRunnable("User 2");
//ThreadStartRunnable c = new ThreadStartRunnable();
ThreadStartRunnable t1 = new ThreadStartRunnable();
t1.createThread("Child 1");
t1.createThread("Child 2");
for(int i=0;i<=5;i++)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("The cirrent Thread is " + t.getName()+ " and thread ID is " + t.getId());
}
}
}
输出:
当前线程是Child 2,线程ID为9
当前线程是Child 2,线程ID为9
当前线程是main,线程ID为1
当前线程是Child 2,线程ID为9
当前线程是Child 2,线程ID为9
当前线程是Child 2,线程ID为9
当前线程是Child 2,线程ID为9
当前线程是Child 2,线程ID为9
当前线程是Child 2,线程ID为9
当前线程是main,线程ID为1
当前线程是Child 2,线程ID为9
当前线程是Child 2,线程ID为9
当前线程是Child 2,线程ID为9
当前线程是Child 2,线程ID为9
当前线程是main,线程ID为1
当前线程是main,线程ID为1
当前线程是main,线程ID为1
当前线程是main,线程ID为1
ThreadStartRunnable
实例,或者将你的代码更改为在单个ThreadStartRunnable
实例中有多个Thread
。 - wns349