1.方法 |
- sleep方法
可以调用Thread的静态方法:
//使当前线程休眠(暂时停止执行millis毫秒)
public static void sleep(long millis)throws InterruptedException
//由于是静态方法,sleep可以由类名直接调用:
Thread.sleep(...)
Thread/TestInterrupt.java
join方法
合并某个线程 Thread/TestYield.javayield方法
让出CPU,给其他线程执行的机会 Thread/TestYield.java
1.实例 |
import java.util.*;
public class testInterrupt{
public static void main(String[] args){
MyThread thread = new MyThread();
thread.start();
try(Thread.sleep(1000);)
catch(InterruptedException e){}
Thread.interrupt();
}
}
class MyThread extends Thread{
public void run[]{
vhile(true){
System.out.println("****"+new Date()+"****");
try{
sleep(1000);
}catch(InterruptedException e){
return;
}
}
}
}
- 每隔一秒钟把系统时间打印一次,用sleep的时候必须写try catch,不能再run()方法添加through exception,因为run()是重写的方法,不能抛出比被重写方法不同的异常
public class TestJoin{
public static void main(String[] args){
MyThread2 t1=new MyThread2("t1");
t1.start();
try(t1.join();)
catch(InterruptedException e){}
for(int i = 1; i<=10;i++){
System.out.println("i am main thread");
}
}
}
class Mythread2 extends thread{
MyThread2(String s){
super(s);
}
public void run(){
for(int i =1;i<=10;i++){
System.out.println("i am "+getName());
try{
sleep(1000);
}
catch(InterruptedException e){
return;
}
}
}
}
结果
yeild方法
- 让出一会儿,时间由CPU分配
3.优先级 |
public class TestPriority{
public static void main(String[] args){
Thread t1=new Thread(new T1());
Thread t2=new Thread(new T2());
//设置优先级
t1.setPriority(Thread.NORM_PRIORITY +3);
t1.start();
t2.start();
}
}
class T1 implements Runnable{
public void run(){
for(int i=0;i<1000;i++){
System.out.println("T1:"+i);
}
}
}
class T2 implements Runnable{
public void run(){
for(int i=0;i<1000;i++){
System.out.println("------T2:"+i);
}
}
}
执行结果:
不设置优先级执行结果: