java查看线程名称_java笔记--查看和修改线程名称

查看和修改线程名称

java是一种允许并发控制的语言,在我们编写的程序的时候,总是伴随着多个线程的执行,

但是背后运行的是什么线程,我们是看不到的,那么又该如何才能知道有哪些线程在运行呢?

另外正所谓"人如其名",很多时候我们查看到系统在运行的线程的名字可读性并不是很好,

所以我们可以根据此线程的功能来为线程换一个名称

在这里主要用到的方法有:

getName():获取当前线程的名称

setName();设置当前线程的名称

getID():返回当前线程的标识符

getThreadGroup:获得当前线程所在的线程组

注:新建的线程的ID是由系统自动分配的,不可指定,但是其名称可通过setName()设置;

代码实例:

package com.xhj.thread;

import java.util.Scanner;

/**

* 查看和修改线程名称

*

* @author XIEHEJUN

*

*/

public class ModifyThreadName implements Runnable {

@Override

public void run() {

}

/**

* 获取并打印出当前所有的线程

*

* @return

*/

public static Thread[] getThreads() {

ThreadGroup group = Thread.currentThread().getThreadGroup();

Thread[] threads = new Thread[group.activeCount()];

group.enumerate(threads, false);

System.out.println("当前运行的线程有:");

System.out.println("线程ID" + "\t线程名称");

for (Thread thread : threads) {

System.out.println(thread.getId() + "\t" + thread.getName());

}

return threads;

}

/**

* 程序数据输入口

*

* @return

*/

public static String input() {

Scanner sc = new Scanner(System.in);

String str = sc.next();

return str;

}

/**

* 查看,修改,新建线程 在新建线程时,线程的ID是由系统自动分配的

*

* @param id

* @param threads

*/

public static void modifyName(int id, Thread[] threads) {

try {

int count = -1;

for (Thread thread : threads) {

if (thread.getId() == (long) id) {

System.out.println("请输入您修改好了的名称:");

thread.setName(input());

break;

} else {

count++;

}

}

if (count == threads.length - 1) {

System.out.println("没有这个线程,将为您新建一个线程,请输入线程的名称:");

Thread new_thread = new Thread(input());

new_thread.start();

}

} catch (Exception e) {

System.out.println(e.getMessage());

}

}

public static void main(String[] args) {

try {

Thread[] threads = getThreads();

System.out.println("请输入您要修改的线程的ID:");

int n = Integer.parseInt(input());

modifyName(n, threads);

getThreads();

} catch (Exception e) {

System.out.println("2" + e.getMessage());

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值