zoukankan      html  css  js  c++  java
  • java笔记查看和修改线程名称

    查看和修改线程名称

      --如果朋友您想转载本文章请注明转载地址"http://www.cnblogs.com/XHJT/p/3893797.html  "谢谢--

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

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

    (请查看上一篇文章《获取JVM所有线程》"http://www.cnblogs.com/XHJT/p/3890280.html "这里就不多说了-_-)

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

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

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

    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());
    }
    }

    }

    知识重在总结和梳理,只有不断地去学习并运用,才能化为自己的东西。由于本人进阶猿类时间尚短,故此博客即是我学习,工作的笔记,也是和大家交流,相互提升技术的平台~希望大家不吝赐教~~ --但管努力,莫问前程,事在人为,功不唐捐。--和佑博客园
  • 相关阅读:
    Neutron LBaaS Service(2)—— Neutron Services Insertion Model
    Gevent工作原理(转)
    异步IO/协程/数据库/队列/缓存(转)
    IO多路复用(转)
    pytz库时区的坑(转)
    Python3.0的新特性(原创)
    Dockerfile 中的 CMD 与 ENTRYPOINT(转)
    RESTful及API设计(原创)
    RESTful服务最佳实践(转)
    Flask restful源码分析(原创)
  • 原文地址:https://www.cnblogs.com/XHJT/p/3893797.html
Copyright © 2011-2022 走看看