一、线程停止:
1.不推荐使用jdk提供的stop()、destroy()方法。【已废弃】
2.推荐线程自己停下,建议使用一个标识位进行终止变量,当flag=false,则终止线程运行
//测试stop
//1.建议线程正常停止--》利用次数,不建议死循环
//2.建议使用一个标识符
public class TestStop implements Runnable{
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("run----->" + i++);
}
}
public void stop(){
this.flag = false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main---->" + i);
if (i==900){
testStop.stop();
System.out.println("线程停止了");
}
}
}
}
二、线程休眠:
1.sleep (时间)指定当前线程阻塞的毫秒数;
2. sleep存在异常InterruptedException;
3.sleep时间达到后线程进入就绪状态;
4.sleep可以模拟网络延时,倒计时等。
5.每一个对象都有一个锁,sleep不会释放锁;
public class TestSleep1 {
public static void main(String[] args) {
try {
tenDown();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//模拟倒计时
public static void tenDown() throws InterruptedException {
int num = 10;
while (true){
Thread.sleep(1000);
System.out.println(num--);
if (num == 0){
break;
}
}
}
}
public static void main(String[] args) {
//打印当前系统时间
Date date = new Date(System.currentTimeMillis());//获取系统当前时间
while (true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
date = new Date(System.currentTimeMillis());//更新系统时间
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
三、线程礼让:
1.礼让线程,让当前正在执行的线程暂停,但不阻塞
2.将线程从运行状态转为就绪状态
3.让cpu重新调度,礼让不一定成功!看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{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+ "线程开始");
Thread.yield();//礼让
System.out.println(Thread.currentThread().getName()+ "线程结束");
}
}
四、线程强制执行:
Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 1; i <= 100 ; i++) {
System.out.println("线程VIP来了" + i);
}
}
public static void main(String[] args) {
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
for (int i = 1; i < 1000; i++) {
if (i ==100){
try {
thread.join();//插队
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("main" + i);
}
}
}
五、观测线程状态:

public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("////////");
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state);//NEW
//观察启动后
thread.start();//启动线程
state = thread.getState();
System.out.println(state);//Run
while (state != Thread.State.TERMINATED){//只要线程不终止,就一直输出状态
Thread.sleep(100);
state = thread.getState();//更新线程状态
System.out.println(state);
}
}
}
浙公网安备 33010602011771号