1、sleep()方法
sleep()是一个静态方法,可以通过类名直接调用,会抛出InterruptedException
public class testSleep {
public static void main(String[] args) {
subThread st = new subThread();
Thread t = new Thread(st);
t.start();
try {
//主进程sleep5s,然后调用thread类的interrupt方法,
//t catch到InterruptedException,结束死循环
Thread.sleep(5000);
t.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class subThread implements Runnable{
public void run() {
while(true){
System.out.println("subThread is running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
}
输出应该为5行“subThread is running”
2、join()方法
将一个进程合并到另一个进程中,相当于直接调用run()方法
public class testJoin {
public static void main(String[] args) throws InterruptedException {
subThread1 st = new subThread1();
Thread t = new Thread(st);
System.out.println("MainThread:1");
t.start();
t.join();
System.out.println("MainThread:2");
}
}
class subThread1 implements Runnable{
public void run() {
for(int i=0;i<3;i++){
System.out.println("subThread:"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
运行结果为:MainThread:1
subThread:0
subThread:1
subThread:2
MainThread:2
3、yield()方法
yield()方法用于让出cpu时间片给其他进程
4、setPriority()和getPriority()
设置进程优先级,优先级越高得到的cpu执行的时间片就越多,具体多少由操作系统分配
进程的优先级最高为10,最低为1,缺省值为5