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:1subThread:0
subThread:1
subThread:2
MainThread:2
3、yield()方法
yield()方法用于让出cpu时间片给其他进程
4、setPriority()和getPriority()
设置进程优先级,优先级越高得到的cpu执行的时间片就越多,具体多少由操作系统分配
进程的优先级最高为10,最低为1,缺省值为5
本文详细介绍了Java中线程控制的基本方法,包括sleep()、join()、yield()及优先级设置等,通过实例演示了如何使用这些方法来实现线程间的同步与调度。

871

被折叠的 条评论
为什么被折叠?



