线程状态转换:
创建->start()->就绪状态<-->调度->运行状态->终止
|箭头 |箭头
|向上 |向下
阻塞解除<-阻塞状态<—导致阻塞的事件
·sleep方法
·可以调用Thread的静态方法:
public static void sleep(long millis) throws InterruptedException
使得当前线程休眠(暂停执行millis毫秒)
·由于是静态方法,sleep可由类名直接调用:
Thread.sleep(....)
举例:
注释:把MyThread线程执行完了再执行主线程
·yield方法
.让出CPU,给其他线程执行的机会
举例:
创建->start()->就绪状态<-->调度->运行状态->终止
|箭头 |箭头
|向上 |向下
阻塞解除<-阻塞状态<—导致阻塞的事件
·sleep方法
·可以调用Thread的静态方法:
public static void sleep(long millis) throws InterruptedException
使得当前线程休眠(暂停执行millis毫秒)
·由于是静态方法,sleep可由类名直接调用:
Thread.sleep(....)
举例:
<span style="font-size:14px;">public class TestTnterrupt {
public static void main(String args[]) {
MyThread myThread = new MyThread();
thread.start();
try{Thread.sleep(10000);}
catch{InterruptedException e}{}
thread.interrupt();//终止线程
}
}
class MyThread extends Thread {
public void run(){
while(true){
System.out.println("...."+new Date()+".....");
try{
sleep(1000);
}catch(InterruptedException e){
return;
}
}
}
}</span>
.join方法
·合并某个线程
举例:
<span style="font-size:14px;">public class TestJoin {
public static void main(String args[]) {
MyThread thread = new MyThread("adcdb");
thread.start();
try {
thread.join();
}catch(InterruptedException e) {}
for(int i=0;i<10;i++) {
System.out.println("i am main thread");
}
}
}
class MyThread extends Thread {
MyThread(String s) {
super(s);
}
public void run(){
for(int i=0;i<10;i++) {
System.out.println("i am "+getName());
}
try {
sleep(1000);
}catch(InterruptedException e) {
return;
}
}
}
</span>
注释:把MyThread线程执行完了再执行主线程
·yield方法
.让出CPU,给其他线程执行的机会
举例:
<span style="font-size:14px;">public class TestYield {
public static void main(String args[]) {
MyThread t1 = new MyThread("t1");
MyThread t2 = new MyThread("t2");
t1.start();
t2.start();
}
}
class MyThread extends Thread {
MyThread(String s) {
super(s);
}
public void run() {
for(int i=0;i<=100;i++) {
System.out.println(getName()+": "+i);
if(i%10==0) {
yield();
}
}
}
}</span>