线程分组 | 守护线程 | 线程优先级

xiaoxiao2021-02-28  97

线程分组         线程分组可以理解为一些线程的分类。在多线程的程序当中,在调试或者打印日志的时候,众多的线程一般很难区分开来。但是通过线程的groupName和threadName可以清晰的看出是哪个线程。但是首先你需要给线程或线程组命一个清晰明了的名字。

        下面上一个demo:

public class ThreadGroupName implements Runnable { public static void main(String[] args) { ThreadGroup tg = new ThreadGroup("PrintGroup"); Thread t1 = new Thread(tg, new ThreadGroupName(), "T1"); Thread t2 = new Thread(tg, new ThreadGroupName(), "T2"); t1.start(); t2.start(); System.out.println(tg.activeCount()); tg.list(); } @Override public void run() { String groupAndName = Thread.currentThread().getThreadGroup().getName() + "-" + Thread.currentThread().getName(); while (true) { System.out.println("I am " + groupAndName); try { Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } } } }

守护线程         从名字就可以看出来,这一类线程是为了某些线程而存在的。         守护线程通常为一些后台服务性的线程,如:GC线程、JIT线程等。这些线程在普通线程退出后,自动结束生命周期。         对于守护线程的创建,比普通线程多的一个操作就是:在线程启动之前,设置setDaemon(true)就可以了。demo如下:

public class DaemonDemo { public static class DaemonT extends Thread { @Override public void run() { while (true) { System.out.println("I am alive"); try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } } } } public static void main(String[] args) throws InterruptedException { Thread t = new DaemonT(); t.setDaemon(true); t.start(); Thread.sleep(2000); } } 线程优先级         Java中的线程优先级是从1-10之间的。当我们创建一个线程时,默认的优先级是5(NORM_PRIORITY)。在Thread类中也有以下常量定义: /** * The minimum priority that a thread can have. */ public final static int MIN_PRIORITY = 1; /** * The default priority that is assigned to a thread. */ public final static int NORM_PRIORITY = 5; /** * The maximum priority that a thread can have. */ public final static int MAX_PRIORITY = 10;        对于线程设置的优先级,优先级高的并不一定在优先级低的之前执行。只是说让其执行的可能性更大一些。 public class PriorityDemo { public static class HightPriority extends Thread { static int count = 0; @Override public void run() { while(true) { synchronized (PriorityDemo.class) { count++; if(count > 10000000) { System.out.println("HightPriority is completed"); break; } } } } } public static class LowPriority extends Thread { static int count = 0; @Override public void run() { while(true) { synchronized (PriorityDemo.class) { count++; if(count > 10000000) { System.out.println("LowPriority is completed"); break; } } } } } public static void main(String[] args) { HightPriority high = new HightPriority(); LowPriority low = new LowPriority(); high.setPriority(Thread.MAX_PRIORITY); low.setPriority(Thread.MIN_PRIORITY); low.start(); high.start(); } } 链接: http://moguhu.com/article/detail?articleId=25

转载请注明原文地址: https://www.6miu.com/read-35357.html

最新回复(0)