1.终止线程的方法
通常会使用一个外部标志位来终止某一线程,不建议使用JDK提供的方法。具体代码如下:
public class Stop implements Runnable{
private boolean flag=true;
@Override
public void run() {
int i=0;
if(flag){
System.out.println("新创建的线程正在执行--->"+i++);
}
}
private void stop(){
//设置一个外部标志位结束线程,这是最好的方法
this.flag=false;
}
public static void main(String[] args) throws InterruptedException {
Stop stop = new Stop();
new Thread(stop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("主线程在执行--->"+i);
if(i==900){
stop.stop();
System.out.println("新开的线程停止了");
}
}
}
}
从运行结果可以看到,当i走到900后,新开的那条线程就终止了(一个线程终止后,这个线程就不能再开启了)。
2.线程礼让
当一个线程和另一个线程竞争时,优先抢到了CPU的调度权,此时这个线程让出调度权,两个线程重新回到同一起跑线,开始新一轮的抢夺。
具体代码入下:
public class Yield {
public static void main(String[] args) {
testYield testYield = new testYield();
new Thread(testYield,"线程1").start();
new Thread(testYield,"线程2").start();
}
}
class testYield implements Runnable{
@Override
public void run() {
System.out.println("线程"+Thread.currentThread().getName()+"开始执行");
//礼让不一定成功
Thread.yield();
System.out.println("线程"+Thread.currentThread().getName()+"执行完毕");
}
}
需要说明:礼让不一定成功。
3.Join(插队)
当前线程只有等待插入的线程结束才能继续执行。
代码如下:
public class Join 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 {
Join join = new Join();
Thread thread = new Thread(join);
thread.start();
for (int i = 0; i < 500; i++) {
if(i==200){
thread.join();
}
System.out.println("这是main线程"+i);
}
}
}
运行结果如下:
4.获取线程状态
一共有5种状态(新建,就绪,运行,阻塞,死亡),简单记忆
代码如下:
/*
测试线程转态
*/
public class State {
public static void main(String[] args) {
Thread thread=new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("END!");
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state);
//启动线程
thread.start();
state=thread.getState();
System.out.println(state);
while (state!=Thread.State.TERMINATED){
state=thread.getState();
System.out.println(state);
}
}
}
部分结果如下图: