Thread.currentThread()方法、进程、线程、多线程相关总结(二)

Thread.currentThread()方法
  Thread.currentThread()可以获取当前线程的引用,一般都是在没有线程对象又需要获得线程信息时通过Thread.currentThread()获取当前代码段所在线程的引用。
  
  getId();获取该线程的标识符
  getName();获取该线程名称
  getState();获取线程状态
  boolean isAlive();测试线程是否属于活动状态
  boolean isDaemon();测试线程是否为守护线程
  boolean isInterrupted();测试线程是否已经中断

public class Demo_1 {
	 public static void main(String[] args){
		 MyThread myThread = new MyThread();
			myThread.setName("A");
			myThread.start();
	    }
}
 class MyThread extends Thread {
	
	public MyThread(){
		System.out.println("------" + "构造函数开始" + "------");
		System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
		System.out.println("Thread.currentThread().getId) = " + Thread.currentThread().getId());
		System.out.println("Thread.currentThread().isDaemon() = " + Thread.currentThread().isDaemon());
		System.out.println("Thread.currentThread().isInterrupted()= " + Thread.currentThread().isInterrupted());
		System.out.println("Thread.currentThread().getState() = " + Thread.currentThread().getState());
		System.out.println("Thread.currentThread().isAlive() = " + Thread.currentThread().isAlive());	
		System.out.println("------" + "构造函数结束" + "------");
	}
	@Override
	public void run(){
	
		System.out.println("------" + "run()开始" + "------");
		System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
		System.out.println("Thread.currentThread().getId() = " + Thread.currentThread().getId());
		System.out.println("Thread.currentThread().isDaemon() = " + Thread.currentThread().isDaemon());
		System.out.println("Thread.currentThread().isInterrupted() = " + Thread.currentThread().isInterrupted());
		System.out.println("Thread.currentThread().getState() = " + Thread.currentThread().getState());
		System.out.println("Thread.currentThread().isAlive() = " + Thread.currentThread().isAlive());
		System.out.println("------" + "run()结束" + "------");
		
	}
}


运行结果:

在这里插入图片描述

守护线程

守护线程与普通线程表面上并没有什么区别,只需要通过Thread类提供的方法设置即可。
   void setDaeMon(boolean c)方法
   当参数为true时,该线程为守护线程
 守护线程的特点:
   当线程中只剩下守护线程时,所有守护线程终止
   GC就是运行在一个守护线程上
    注意:设置线程为守护线程,要在该线程启动前设置

import java.io.IOException;

public class Demo_1 {
	 public static void main(String[] args){
		 MyThread myThread = new MyThread();
		 myThread.setDaemon(true);    
		 myThread.start();
			 try {
		           System.in.read();   // 接受输入,使程序在此停顿,一旦接收到用户输入,main线程结束,守护线程自动结束
		       } catch (IOException ex) {}
		   }
 }
 class MyThread extends Thread {
	
	@Override
	public void run(){
		System.out.println("Thread.currentThread().isDaemon() = " + Thread.currentThread().isDaemon());
	}
	
}

猜你喜欢

转载自blog.csdn.net/he_zhen_/article/details/87456835