/**
* Created by xabcd on 2019/2/17.
*/
public class sleep extends Thread
{
public void run(){
loop();
}
public void loop(){
String name = Thread.currentThread().getName();
System.out.println(name+"--->>刚进入loop方法");
for (int i = 0;i<10;i++)
{
try{
Thread.sleep(2000);
}
catch(InterruptedException x){}
System.out.println("name="+name);
}
System.out.println(name+"--->>离开loop方法");
}
public static void main(String[] args)
{
sleep tt =new sleep();
tt.setName("my worker thread");
tt.start();
try{
Thread.sleep(700);
}
catch(InterruptedException x){}
tt.loop();
}
}
my worker thread--->>刚进入loop方法
main--->>刚进入loop方法
name=my worker thread
name=main
name=my worker thread
name=main
name=my worker thread
name=main
name=my worker thread
name=main
name=my worker thread
name=main
name=my worker thread
name=main
name=my worker thread
name=main
name=my worker thread
name=main
name=my worker thread
name=main
name=my worker thread
my worker thread--->>离开loop方法
name=main
main--->>离开loop方法
由于使用sleep方法会抛出一个InterruptedException,所以在程序中需要用try---catch捕获