线程停止、sleep、yield、join和优先级
6、线程停止
-
建议正常停止
-
设置标志位,正常停止线程
-
不建议使用stop和distroy等过时方法或其他JDK不推荐的方法
/*
1、创建类,继承Runnable接口,设置一个类变量flag,重写run方法
2、创建一个停止方法stop,更改flag的状态
3、创建主方法,新建对象,调用start方法,创建循环,循环调用stop方法,停止线程
*/
public class ThreadStop implements Runnable{
private boolean flag = true;
7、线程休眠sleep
-
倒计时10秒
-
打印当前时间
-
使用sleep记得捕获异常就好
//倒计时10秒
import static java.lang.Thread.sleep;
public class ThreadSleep {
public static void main(String[]args) {
try {
new ThreadSleep().tenDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void tenDown() throws InterruptedException {
int num = 10;
while(true){
System.out.println(num--);
Thread.sleep(1000);
if(num<=0){
break;
}
}
}
}
//打印当前时间
import java.text.SimpleDateFormat;
import java.util.Date;
import static java.lang.Thread.sleep;
public class ThreadSleep {
public static void main(String[]args) {
Date startTime = new Date(System.currentTimeMillis());
while (true){
try {
Thread.sleep(1000);//休眠一面
//把系统时间转为简单的格式打印
System.out.println(new SimpleDateFormat("hh:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis());//更新startTime里面的时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
8、线程礼让yield
-
让当前线程暂停,但不阻塞
-
将线程从运行状态转为就绪状态
-
让cpu重新调度,礼让不一定成功,让不让cpu说了算
public class ThreadYield {
public static void main(String[] args) {
//正常运行,礼让成功就是先运行a,再运行b。如不成功就a停止再运行b
new Thread(new MyYield(),"a").start();
new Thread(new MyYield(),"b").start();
}
}
class MyYield implements Runnable{
9、线程插队-Join
-
让当前线程暂停且阻塞
-
插队线程运行结束其他线程才能继续运行
public class ThreadJoin implements Runnable{
10、线程优先级
-
优先级最高为10,最低为1,主函数线程优先级一般为5
-
并不是优先级高就最先执行,还是要看CPU的心情
//优先级最高为10,最低为1,主函数线程优先级一般为5
//并不是优先级高就最先执行,还是要看cpu的心情
public class ThreadPriority implements Runnable{
浙公网安备 33010602011771号