Java Multithreading 2.6. Overview of Thread Groups and Overview of Using

Thread Groups and Using

1, Thread Group

  • Thread Group: Combine multiple threads together.
  • Main role: It can classify and manage a batch of threads. Java allows programs to directly control thread groups.

(1)Create thread class

package cn.itcast_06;
public class MyRunnable implements Runnable {
	@Override
	public void run() {
		for (int x = 0; x < 100; x++) {
			System.out.println(Thread.currentThread().getName() + ":" + x);
		}
	}

}

(2)Test thread class

package cn.itcast_06;

/*
 * Thread group: Combine multiple threads together.
 * It can classify and manage a batch of threads. Java allows programs to directly control thread groups.
 */
Public class ThreadGroupDemo {
Public static void main(String[] args) {
// method1();

// How do we modify the group in which the thread is located?
// Create a thread group
// When creating other threads, specify the group of other threads as our own new thread group.
Method2();

// t1.start();
// t2.start();
}

Private static void method2() {
// ThreadGroup(String name)
ThreadGroup tg = new ThreadGroup("This is a new group");

MyRunnable my = new MyRunnable();
// Thread(ThreadGroup group, Runnable target, String name)
Thread t1 = new Thread(tg, my, "林青霞");
Thread t2 = new Thread(tg, my, "刘意");

System.out.println(t1.getThreadGroup().getName());
System.out.println(t2.getThreadGroup().getName());

/ / Set the background thread by group name, indicating that the thread of the group is a background thread
tg.setDaemon(true);
}

Private static void method1() {
MyRunnable my = new MyRunnable();
Thread t1 = new Thread(my, "林青霞");
Thread t2 = new Thread(my, "Liuyi");
// I don't know if they belong to that thread group, I want to know, what to do
// The method inside the thread class: public final ThreadGroup getThreadGroup()
ThreadGroup tg1 = t1.getThreadGroup();
ThreadGroup tg2 = t2.getThreadGroup();
// The method inside the thread group: public final String getName()
String name1 = tg1.getName();
String name2 = tg2.getName();
System.out.println(name1);
System.out.println(name2);
/ / Through the results we know: threads belong to the main thread group by default
// By the following test, you should be able to see that all threads belong to the same group in the silent case.
System.out.println(Thread.currentThread().getThreadGroup().getName());
}
}

2, the method used

  • thread class inside the method: public final ThreadGroup getThreadGroup ()
  • Thread group inside the method: public final String getName ()
  • System.out.println(Thread.currentThread().getThreadGroup().getName());
  • ThreadGroup(String name)
  • Thread(ThreadGroup group, Runnable target, String name)
  • by group name Set the background thread to indicate that the threads of the group are background threads: tg.setDaemon(true);