1.常用API
1. getId();获取线程ID,getName();获取线程名。不会重复。
main也是一个线程,任何一个程序都有一个主线程
主线程ID:Thread.currentThread().getId();
主线程Name:Thread.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.setDaemon(true);
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("主线程执行结束——————————");
}
}