线程组

/ 多线程 / 没有评论 / 305浏览

在开发多线程时,可以用ThreadGroup关键字创建一个线程组来方便管理一系列的子线程,线程组可以统一的设置线程的某些属性。

/**
* 管理用户请求
*
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-15 10:44
* @since 1.0.0
*/
public class RequestAdmin extends Thread {

@Override
public void run() {
System.out.println(String.format("thread: %s", Thread.currentThread().getName()));
}
}
/**
* 用户请求
*
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-15 10:44
* @since 1.0.0
*/
public class RequestUser extends Thread {

@Override
public void run() {
System.out.println(String.format("thread: %s", Thread.currentThread().getName()));
}
}
/**
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-20 13:35
* @since 1.0.0
*/
public class Test {
public static void main(String[] args) {
RequestAdmin requestAdmin = new RequestAdmin();
RequestUser requestUser = new RequestUser();
ThreadGroup group = new ThreadGroup("request");
Thread threadAdmin = new Thread(group, requestAdmin);
Thread threadUser = new Thread(group, requestUser);
threadAdmin.start();
threadUser.start();
}
}
thread: Thread-3
thread: Thread-2

在使用上和正常操作线程一样没什么区别,但有时我们的确会用到线程组。例如如果我们要将某些线程设置为守护线程的话,那我们只需要设置这个线程所在的线程组就可以了,那么这个线程组里的线程就统统都成了守护线程。

/**
* 管理用户请求
*
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-15 10:44
* @since 1.0.0
*/
public class RequestAdmin implements Runnable {

@Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("是否是守护线程: %s\tthread: %s", Thread.currentThread().getName(), Thread.currentThread().isDaemon()));
}
}
/**
* 用户请求
*
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-15 10:44
* @since 1.0.0
*/
public class RequestUser implements Runnable {

@Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("是否是守护线程: %s\tthread: %s", Thread.currentThread().getName(), Thread.currentThread().isDaemon()));
}
}
/**
* @author Sama
* @author admin@jilinwula.com
* @date 2017-03-20 13:35
* @since 1.0.0
*/
public class Test {
public static void main(String[] args) throws InterruptedException {
RequestAdmin requestAdmin = new RequestAdmin();
RequestUser requestUser = new RequestUser();
ThreadGroup group = new ThreadGroup("request");
group.setDaemon(true);
Thread threadAdmin = new Thread(group, requestAdmin);
Thread threadUser = new Thread(group, requestUser);
threadAdmin.start();
threadUser.start();
for (int i = 3; i > 0; i--) {
System.out.println(String.format("倒计时:%s", i));
Thread.sleep(1000);
}
}
}
倒计时:3
倒计时:2
倒计时:1
是否是守护线程: Thread-0	thread: false
是否是守护线程: Thread-1	thread: false