gpt4 book ai didi

java - Java中一个对象可以创建多个线程吗

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:26:39 26 4
gpt4 key购买 nike

我是多线程的新手,在练习时我编写了以下代码。我想每次调用 createThred 方法时都创建一个新线程。但是,使用下面给出的代码,每次调用 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());
}




}

}

OUTPUT:

The current Thread is Child 2 and thread ID is 9

The current Thread is Child 2 and thread ID is 9

The cirrent Thread is main and thread ID is 1

The current Thread is Child 2 and thread ID is 9

The current Thread is Child 2 and thread ID is 9

The current Thread is Child 2 and thread ID is 9

The current Thread is Child 2 and thread ID is 9

The current Thread is Child 2 and thread ID is 9

The current Thread is Child 2 and thread ID is 9

The cirrent Thread is main and thread ID is 1

The current Thread is Child 2 and thread ID is 9

The current Thread is Child 2 and thread ID is 9

The current Thread is Child 2 and thread ID is 9

The current Thread is Child 2 and thread ID is 9

The cirrent Thread is main and thread ID is 1

The cirrent Thread is main and thread ID is 1

The cirrent Thread is main and thread ID is 1

The cirrent Thread is main and thread ID is 1

最佳答案

它总是说 Child 2 的原因是因为您正在打印 Thread t 成员的名称,这是最后创建的线程。

替换:

System.out.println("当前线程为"+ t.getName() + ",线程ID为"+ t.getId());

System.out.println("当前线程是"+ Thread.currentThread().getName() + ",线程ID是"+ Thread.currentThread().getId());

否则可以使用相同的可运行对象: Initializing two threads with the same instance of a runnable

关于java - Java中一个对象可以创建多个线程吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23135412/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com