Java中的并发知识点梳理

xiaoxiao2021-02-28  85

首先,什么是线程?

     大家可能都比较熟悉操作系统的中的多任务:在同一刻运行多个程序的能力。而多线程程序在较低的层次上扩展了多任务的概念:一个程序同时执行多个任务。通常,每一个任务称为一个线程(Thread)。

线程该如何创建?

    1.继承Thread类,然后重写run()方法,

      Thread类是在java.lang包中定义的。一个类只要继承了Thread类同时覆写了本类中的run()方法就可以实现多线程操作了。

首先新建一个MyThread类继承自Thread类,重写run()方法:

class Mythread extends Thread { @Override public void run() { take code } }然后,构造一个子类的对象,并调用start方法。

    2.将任务代码移到实现了Runnable接口的类的run方法中。这个接口非常简单,只有一个方法:

public interface Runnable { void run(); }可用lambda表达式建立一个实例:

Runnale r = () -> {task code};

接着,由Runnable创建一个Thread对象:

Thread t  = new Thread(r);

最后,启动线程:

t.start();

什么是中断线程?

   线程终止的条件:1.顺利执行完毕;

   2.出现了方法中没有捕获的异常。

   当对一个线程调用interrupt方法时,线程的中断状态将被置位,每个线程应该不时地检查这个标志,以判断线程是否被中断。如果线程被阻塞的同时又有中断发生,便会产生InterruptedException异常,我们需要保证run方法能捕获到这个异常,所以线程的run方法应该这样写来防止线程被终止:

Runnable r = () -> { try { ... while(!Thread.currentThread().isInterrupted() && more work to do) { do more work } } catch(InterruptedException e) { //thread was interrupted during sleep or wait } finally { cleanup,if required } //exiting the run method terminates the thread };

持续更新中。。。。。。。

转载请注明原文地址: https://www.6miu.com/read-84569.html

最新回复(0)