线程的一些属性

名字

给以给线程取一个响亮的名字,便于排查问题,默认为Thread-${一个数字}这个样子

  • 设置名字
threadA.setName("欢迎关注微信公号'大雄和你一起学编程'");
  • 获取名字
threadA.getName();

是否是守护线程(daemon)

为其他线程服务的线程可以是守护线程,守护线程的特点是如果所有的前台线程死亡,则守护线程自动死亡。

非守护线程创建的线程默认为非守护线程,守护则默认为守护

  • set
threadA.setDaemon(true);
  • get
threadA.isDaemon();

线程优先级(priority)

优先级高的线程可以得到更多cpu资源, 级别是1-10,默认优先级和创建他的父线程相同

set

threadA.setPriority(Thread.NORM_PRIORITY);

get

threadA.getPriority()

所属线程组

可以把线程放到组里,一起管理

设置线程组

Thread的构造里边可以指定

ThreadGroup threadGroup = new ThreadGroup("欢迎关注微信公号'大雄和你一起学编程'");
Thread thread = new Thread(threadGroup, () -> {
    System.out.println("欢迎关注微信公号'大雄和你一起学编程'");
});

拿到线程组

thread.getThreadGroup()

基于线程组的操作

ThreadGroup threadGroup1 = thread.getThreadGroup();
System.out.println(threadGroup1.activeCount()); // 有多少活的线程
threadGroup1.interrupt();                       // 中断组里所有线程
threadGroup1.setMaxPriority(10);                // 设置线程最高优先级是多少

results matching ""

    No results matching ""