Vij*_*raj 2 java multithreading
我对多线程很陌生,所以我要问的问题可能很简单.
在我的程序中,有两个线程,一个是主线程,第二个是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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,程序的输出是,
Thread[main,5,main]
Thread[mythread,5,main]
Run Code Online (Sandbox Code Playgroud)
我知道输出意味着什么.
但我想将mythread的线程组更改为我自己而不是main.我怎样才能做到这一点?
什么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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2228 次 |
| 最近记录: |