JAVA高级基础(65)---线程名称及获取系统当前线程

版权声明:如需转载请标明出处 https://blog.csdn.net/yj201711/article/details/85028442

线程名称

设置名称:Thread(Runnable target,String name)
                 getName();返回线程名称
                 getId();获取线程的ID
                 setName(String name);设置线程名称

在创建线程时,系统会默认为每个线程分配一个名称:Thread-0  Thread-1

获取当前执行线程

                       Thread.currentThread();返回当前执行线程的对象

package org.lanqiao.thread.demo;

public class ThreadName {
	public static void main(String[] args) {
		Thread  t1 = new Thread("线程一") {
			public void run() {
				/*try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}*/
				for(int i= 0 ; i < 5; i++) {
					
					System.out.println(Thread.currentThread().getName());
				}
			}
			
		};
		t1.setName("线程壹");
		
		System.out.println( t1.getName());
		System.out.println(t1.getId());
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i= 0 ; i < 5; i++) {
					if(i % 3 == 0) {
						try {
							t1.join();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					
					System.out.println(Thread.currentThread().getName());
				}
			}
			
			
		},"线程二");
		t2.setName("线程贰");
		System.out.println(t2.getName());
		System.out.println(t2.getId());
		System.out.println("---------------------");
		//获取当前执行线程对象
		Thread  currentThread = Thread.currentThread();
		System.out.println(currentThread.getName());
		t1.setDaemon(true);
		t1.start();
		System.out.println("------t1"+t1.isAlive());
		System.out.println("t1"+t1.isDaemon());
		t2.start();
		System.out.println("----t2"+t2.isAlive());
		System.out.println("t2"+ t2.isDaemon());
	}
}

猜你喜欢

转载自blog.csdn.net/yj201711/article/details/85028442
今日推荐