线程停止
//测试停止线程
//1.建议线程正常停止,-->利用次数,不建议死循环
//2.建议使用一个标志位-->设置一个标志位
//3.不要使用stop或者destroy等过时或者jdk不建议使用的方法
public class TestStop implements Runnable {
//设置一个标志位
private boolean flag=true;
线程休眠
作用:模拟网络延迟的作用:放大问题的发生行
public class TestSleep implements Runnable{
//票数
private int ticketNums=10;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;
//模拟倒计时
public class TestSleep2 {
public static void main(String[] args) {
/* try {
tenDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
模拟倒计时*/
//打印当前时间
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());//更新数据
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//模拟倒计时
public static void tenDown() throws InterruptedException {
int num=10;
while(true){
Thread.sleep(1000);
System.out.println(num--);
if (num <= 0) {
break;
}
}
}
}
线程礼让
线程礼让不一定成功要看CPU的心情
package com.wang1.state;
//测试礼让线程
//礼让不一定成功,看CPU心情
public class TestYield {
public static void main(String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield,"a").start();
new Thread(myYield,"b").start();
}
}
class MyYield implements Runnable{
线程强制执行
我自己的理解:就是必须强行执行的先要执行完毕,类似充钱了,VIP插队
package com.wang1.state;
//测试join方法
public class TestJoin implements Runnable{
线程的优先级
package com.wang1.state;
public class TestPriority {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
MyPriority myPriority=new MyPriority();
Thread t1=new Thread(myPriority);
Thread t2=new Thread(myPriority);
Thread t3=new Thread(myPriority);
Thread t4=new Thread(myPriority);
Thread t5=new Thread(myPriority);
Thread t6=new Thread(myPriority);
//先设置优先级
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(4);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);
t4.start();
t5.setPriority(8);
t5.start();
t6.setPriority(7);
t6.start();
}
}
class MyPriority implements Runnable{
守护线程
上帝守护你,如果你消亡了,上帝也会结束
package com.wang1.state;
//测试守护线程
//上帝守护
public class TestDaemon {
public static void main(String[] args) {
You you = new You();
God god=new God();
Thread thread=new Thread(god);
thread.setDaemon(true);//调用守护线程
thread.start();
new Thread(you).start();
}
}
//上帝守护
class God implements Runnable{