多线程常用API、守护线程及非守护线程

1.常用API

1. getId();获取线程ID,getName();获取线程名。不会重复。

main也是一个线程,任何一个程序都有一个主线程

主线程IDThread.currentThread().getId();

主线程NameThread.currentThread().getName();

2.Thread.sleep(2000);休眠,后面是ms

3. Thread.currentThread();获取当前线程

4. Thread(Runabler,String name);

Class CreateThreadDemo05 extends Thread{
	@Override
	publicvoidrun(){
	for(inti=0;i<30;i++){
		try{
			Thread.sleep(2000);
		}catch(InterruptedException e){
			e.printStackTrace();
		}
		System.out.println(getId()+"子线程,i:"+i);
	};
	}
}
Public class ThreadDemo05{
	Public static void main(String[] args){
		//获取主线程ID
		System.out.println("主线程ID:"+Thread.currentThread().getId());
		System.out.println("主线程Name:"+Thread.currentThread().getName());
		for(int i=0;i<2;i++){
			CreateThreadDemo05demo05=newCreateThreadDemo05();
			Thread thread=new Thread(demo05,"重命名05");
			thread.start();
		};
		//获取到当前线程
		Thread.currentThread();
	}
}

2.守护线程与非守护线程

守护线程(main相关、gc线程)、非守护线程(用户线程)

守护线程特征:和主线程一起销毁

非守护线程特征:和主线程互不影响

设置守护线程:Thread.setDaemontrue;

Public class shThread01{
Public static void main(String[] args){
	Thread thread=new Thread(new Runnable(){
		@Override
		Public void run(){
			for(inti=0;i<20;i++){
				try{
					Thread.sleep(1000);
				}catch(InterruptedException e){
					e.printStackTrace();
				}
				System.out.println("子线程,i"+i);
			}
		}
	});
	thread.setDaemon(true);
	thread.start();
	System.out.println("主线程执行结束——————————");
	}
}


版权声明:本文为weixin_42645212原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。