线程状态+线程方法
停止线程
一般采用一个标志位在外部方法修改,让线程终止
e.g. 在main线程跑到900次时让Thread线程终止
public class TestStop implements Runnable{
//1.设置一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while(flag){
System.out.println("run..." + i++);
}
}
//2. 设置一个停止的方法转换标志位
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("线程该停止了");
}
//调用stop方法切换标志位让线程停止
}
}
}
线程休眠
线程礼让
意思是让它重新回到和其他进程同一个起点,重新一起调度
public class TestYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "线程start");
Thread.yield();
System.out.println(Thread.currentThread().getName() + "线程end");
}
public static void main(String[] args) {
TestYield testYield = new TestYield();
new Thread(testYield,"a").start();
new Thread(testYield,"b").start();
}
}
礼让成功 | 礼让不成功 |
---|---|
线程合并(Join)
下面代码意思是主线程开始是和thread线程一块竞争,在主线程走到200时,thread线程join了,就是插队了,知道插队的线程走完之后,才让主线程走
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("插队线程来了" + i);
}
}
//类似插队
public static void main(String[] args) throws InterruptedException {
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
for (int i = 0; i < 500; i++) {
if(i == 200) {
thread.join();
}
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) {
e.printStackTrace();
}
System.out.println("//");
}
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state);
//观察启动后
thread.start();
state = thread.getState();
System.out.println(state);
while (state != Thread.State.TERMINATED) {
//只要线程不终止,就一直输出状态
Thread.sleep(100);
state = thread.getState();
System.out.println(state);
}
//这里不会再运行,死亡之后的线程无法再次启动,下面这句话会报错
thread.start();
}
}
输出结果