Java开发基础-线程-线程常用的静态方法—01

  1. 获取运行当前方法的线程 :

        static Thread currentThread()

     下面通过简单实例演示

public class ThreadDemo4 {
	
	public static void main(String[] args) {
		Thread t = Thread.currentThread();
		System.out.println("运行main方法的线程是:"+t);
		dosome();
		
		Thread myth =new Thread(){

			@Override
			public void run() {
				Thread t = Thread.currentThread();
				System.out.println("自定义线程:"+t);
				dosome();
			}
			
		};
		
		myth.start();
	}	
	
	public static void dosome(){
		//获取运行当前方法的线程
		Thread t = Thread.currentThread();
		System.out.println("运行dosome方法的线程是:"+t);
	}

}

运行控制台输出:

  

格式说明:
Thread[main,5,main]--[线程名 ,线程优先级,所在主线程]

线程的名字main  它的优先级是5,主线程的名称是main。
  • 获取线程属性信息
    public class ThreadDemo5 {
    	
    	public static void main(String[] args) {
    		// 获取运行main方法的线程
    		Thread t = Thread.currentThread();
    
    		// 获取ID
    		// 返回此线程的标识符。线程ID是创建该线程时生成的正整数。
    		// 线程ID是唯一的,并且在其生命周期内保持不变。当线程终止时,可以重新使用该线程ID。
    		long id = t.getId();
    		System.out.println("id:" + id);
    
    		// 获取名字
    		String name = t.getName();
    		System.out.println("name:" + name);
    
    		// 获取线程的优先级
    		int priority = t.getPriority();
    		System.out.println("优先级:" + priority);
    
    		// 线程是否存活
    		boolean isAlive = t.isAlive();
    		System.out.println("isAlive:" + isAlive);
    
    		// 是否是守护线程
    		boolean isDaemon = t.isDaemon();
    		System.out.println("isDaemon:" + isDaemon);
    
    		// 是否被中断
    		boolean isInter = t.isInterrupted();
    		System.out.println("isInterrupted:" + isInter);
    
    	}
    
    }

当需要获取对应线程信息并对其做操作时可使用这些静态方法。

猜你喜欢

转载自blog.csdn.net/Coder_Boy_/article/details/80373787