线程的停止方法很多
,由本身自带的stop和destroy方法,但是这些方法已经在jdk中停止使用了。我们可以通过1设置标志位,,2使用次数停止
package com.heal.Thread_test;
public class TestStop implements Runnable {
private Boolean flag=true;
@Override
public void run() {
int i=0;
while(flag){
System.out.println("run----------------Thread"+i++);
}
}
// 设置一个公开的方法用来停止线程,其实就是改变flag的值
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("mian"+i);
if (i==900){
//调用stop方法改变flag的值,使线程停止
testStop.stop();
System.out.println("该线程停止了");
}
}
}
}
线程的休眠sleep()方法****
package com.heal.Thread_test;
//模拟一个倒计时
public class TestSleep {
public static void main(String[] args) throws InterruptedException {
tenDown();
}
public static void tenDown() throws InterruptedException {
int num=10;
while(true){
Thread.sleep(1000);
System.out.println(num--);
if (num<0){
break;
}
}
}
}
线程礼让yield()方法*
package com.heal.Thread_test;
public class TestYield {
public static void main(String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield,"a").start();//创建一个a线程
new Thread(myYield,"b").start();//创建一个b线程
}
}
class MyYield implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "线程开始");
Thread.yield();//调用线程的礼让方法
System.out.println(Thread.currentThread().getName() + "线程结束");
}
}
**
线程jion()方法,强行插队
此线程执行后再执行其他线程,其他的线程处于阻塞的状态
package com.heal.Thread_test;
public class TestJion implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("线程VIP来了"+i);
}
}
public static void main(String[] args) throws InterruptedException {
//启动vip线程
TestJion testJion=new TestJion();
Thread thread1=new Thread(testJion);
thread1.start();
//主线程
for (int i = 0; i < 1000; i++) {
if (i==200){
thread1.join();
}
System.out.println("main"+i);
}
}
}
运行的结果为:在main199时,开始切换为vip线程,一直执行vip线程直到vip999,再接着main200执行
线程的状态
package com.heal.Thread_test;
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){
e.printStackTrace();
}
}
System.out.println("");
});
// 观察状态
Thread.State state=thread.getState();
System.out.println(state);//NEW因为还没有调用start方法
// 观察启动后
thread.start();//启动线程
state=thread.getState();//RUN
System.out.println(state);
while (state!=Thread.State.TERMINATED){
Thread.sleep(100);
state=thread.getState();
System.out.println(state);
}
}
}