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());
	}
	
}
  • 8
    点赞
  • 55
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值