gpt4 book ai didi

java - Java中如何更改线程组的名称?

转载 作者:行者123 更新时间:2023-12-02 11:02:15 26 4
gpt4 key购买 nike

我对多线程非常陌生,所以我要问的问题可能很简单。

在我的程序中,有两个线程,一个是ma​​in线程,第二个是mythread

package multithreading;

public class ThreadDemo {
public static void main(String args[]) {
System.out.println(Thread.currentThread());
new MyThread();
try {
for(int i = 1; i<=5; i++) {
Thread.sleep(1000);
}

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}

class MyThread extends Thread {
public MyThread() {
start();
}

public void run() {
Thread.currentThread().setName("mythread");
System.out.println(Thread.currentThread());
for(int i = 1; i<=5; i++) {
try {
Thread.sleep(500);
//System.out.println("MyThread i value "+i);

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

现在,程序的输出是,

Thread[main,5,main]
Thread[mythread,5,main]

我知道输出的含义。

但是我想将mythread的线程组更改为我自己的,而不是ma​​in。我怎样才能做到这一点?

Java中使用什么方法来改变线程的线程组?

更改线程组会有什么问题吗?

最佳答案

我建议实现 Runnable 而不是扩展 Thread。然后,您可以轻松地创建一个具有自己的组的新线程:

public class ThreadDemo {
public static void main(String args[]) {
System.out.println(Thread.currentThread());
Runnable r = new MyRunnable();
new Thread(new ThreadGroup("my group"), r).start();
try {
for (int i = 1; i <= 5; i++) {
Thread.sleep(1000);
}

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

class MyRunnable implements Runnable {

public void run() {
Thread.currentThread().setName("mythread");
System.out.println(Thread.currentThread());
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(500);
//System.out.println("MyThread i value "+i);

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

关于java - Java中如何更改线程组的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17674113/

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