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

1.常用API

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

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

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

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

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

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

4. Thread(Runable r,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("主线程执行结束——————————");
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值