线程的启动方式和终止方式

文章讨论了Java中四种不同的线程中断方式:volatile变量、AtomicBoolean、Interrupt标志以及已废弃的stop方法。volatile和AtomicBoolean确保线程间变量同步,Interrupt设置中断标志,而stop强制中断可能导致数据结构错误或资源未释放。在处理线程中断时,推荐使用Interrupt和相关的异常处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、线程的启动方式

1、自己创建Thread类继承Thread类

自己创建的thread要重写run方法,然后启动自己创建的Thread

public class Thread1 extends Thread{
    @Override
    public void run() {
        while(true) {
            System.out.println("线程1");
        }
    }
}
new Thread1().start();

2、自己创建Runnable类实现Runnable接口

自己创建的Runnable要实现run方法,然后把自己创建的Runnable类传入Thread类中

public class Runnable2 implements Runnable {

    @Override
    public void run() {
        while (true) {
            System.out.println("线程2");
        }
    }
}
new Thread(new Runnable2()).start();

3、Thread的匿名内部类

new Thread(()->{
    while (true) {
        System.out.println("线程3");
    }
}).start();

4、利用线程池(随意)传入Runnable匿名内部类

ExecutorService es4 = Executors.newSingleThreadExecutor();
es4.execute(()->{
    while (true) {
        System.out.println("线程4");
    }
});
es4.shutdown();

5、自己创建Callable实现Callable接口:

类似Runnable,区别在有返回值,返回值借助FutureTask实现,FutureTask会存入线程执行结果

public class Callable5 implements Callable<String> {
    @Override
    public String call() throws Exception {
        Thread.sleep(10000);
        return "result:"+Thread.currentThread().getName();
    }
}
Callable5 c5 = new Callable5();
FutureTask<String> ft5 = new FutureTask<>(c5);
Thread t5 = new Thread(ft5);
t5.start();
try {
    String result = ft5.get();//这里会阻塞主线程,直到线程5执行完,返回结果
    System.out.println(result);
} catch (Exception e) {
    e.printStackTrace();
}

6、利用线程池下的Callable匿名内部类

与线程池的Runnable类似,但是有返回值,返回值存于线程池submit方法的执行结果Future中。

ExecutorService es6 = Executors.newFixedThreadPool(1);
Future<String> f6 = es6.submit(() -> {
    Thread.sleep(10000);
    return "线程6";
});
try {
    f6.get();//这里会阻塞主线程,直到线程6执行完,返回结果
} catch (Exception e) {
    e.printStackTrace();
}
es4.shutdown();

二、线程的终止方式

1、volatile

private static volatile boolean stopFlag = false;//默认不中断

public static void main(String[] args) {
    Thread t1 = new Thread(() -> {
        while (!stopFlag) {
            System.out.println("线程1在执行");
        }
    });
    t1.start();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    new Thread(() -> {
        stopFlag = true;
    }).start();
}

2、AtomicBoolean

private static AtomicBoolean stopFlag = new AtomicBoolean(false);//默认不中断

public static void main(String[] args) {
    Thread t1 = new Thread(() -> {
        while (!stopFlag.get()) {
            System.out.println("线程1在执行");
        }
    });
    t1.start();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    new Thread(() -> {
        stopFlag.set(true);
    }).start();
}

3、Interrupt

public static void main(String[] args) {
    Thread t1 = new Thread(() -> {
        while (!Thread.currentThread().isInterrupted()) {
            System.out.println("线程1在执行");
        }
    });
    t1.start();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    new Thread(() -> {
        t1.interrupt();
    }).start();
}

4、stop

注意stop和interrupt之间的问题:
stop是强制中断,而interrupt不是直接中断,而是做一个中断标识,会做好相关收尾工作再中断。
比如对于一个线程a,当其他线程调用了a的interrupt方法,如果a中在执行wait、sleep等方法,会抛出InterruptedException异常,然后中断。反观stop则会直接中断。

举例说明stop引发问题:
stop对于hashmap扩容直接中断,可能引起数据结构错误。
stop对于io流直接中断,没有正常close关流,会导致内存溢出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值