Day12 _63_获取当前线程对象

给线程起名

* 1. Thread.currentThread();   可以获取到当前线程对象,出现在哪就是获取哪个线程。

* 2. thread.setName();  给该线程起名字

* 3. thread.getName();  获取该线程的名字


* 代码实例
  ```
  package com.shige.Thread;
  import java.util.Currency;

  public class ThreadTest03 {
      public static void main(String[] args) {

            // 获取当前线程对象
            Thread thread=Thread.currentThread(); //主线程

            //给线程起名字
             thread.setName("主线程");
             System.out.println(thread.getName());//输出线程名字



            // 创建线程对象
             Thread thread2=new Thread(new Processor_01());

            //给线程起名字
             thread2.setName("线程1");

           // 创建线程对象
            Thread thread3=new Thread(new Processor_01());

           //给线程起名字
            thread3.setName("线程2");


          //启动线程
          thread2.start();

          thread3.start();
      }
  }

  //定义一个线程
  class Processor_01 implements Runnable{ //实现Runnable接口
       
       //实现run方法
        @Override
        public void run() {
            // 获取当前线程对象
               Thread thread1=Thread.currentThread(); //当前线程
               System.out.println(thread1.getName()); //输出线程名

        }
  }
posted @ 2021-04-07 21:12  失昼  阅读(129)  评论(0)    收藏  举报