一个线程的创建肯定是由另一个线程创建。

  被创建线程的父线程就是创建他的线程。

    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals) {
        if (name == null) {
            throw new NullPointerException("name cannot be null");
        }

        this.name = name;

        Thread parent = currentThread();//父线程
        SecurityManager security = System.getSecurityManager();
        //……
}

一、线程命名和取得

  线程的所有操作方法几乎都在Thread类中定义好了

  从本质上上来讲,多线程的运行状态并不是固定的,唯一的区别就在于线程的名称上。

  起名:尽可能避免重名,或者避免修改名称。

  在thread类中提供如下方法:

    构造方法:public Thread(Runnable target, String name)

    设置名字:public final synchronized void setName(String name)

    取得名字:public final String getName()

  既然线程本身是不缺定的状态,所以如果要取得线程名字的话,那么唯一能做的就是取得当前线程的名字。

  所以在Thread类中有提供如下方法:

    public static native Thread currentThread();

示例1:

003-多线程-基础-其他【命名和取得、休眠、优先级、线程状态、线程中断、最大线程数量、Thread与Jvm虚拟机栈】
class MyThread6 implements Runnable {
    @Override
    public void run() {// 主方法
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + ",i:" + i);
        }
    }
}
View Code

相关文章:

  • 2021-10-10
  • 2022-12-23
  • 2022-12-23
  • 2021-06-05
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-31
  • 2022-12-23
  • 2022-12-23
  • 2021-04-10
  • 2021-08-18
  • 2021-11-24
相关资源
相似解决方案