博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
线程基础知识归纳
阅读量:4315 次
发布时间:2019-06-06

本文共 8586 字,大约阅读时间需要 28 分钟。

1. 进程与线程的区别

  • 进程:是系统进行分配和管理资源的基本单位

  • 线程:进程的一个执行单元,是进程内调度的实体、是CPU调度和分派的基本单位,是比进程更小的独立运

    行的基本单位。线程也被称为轻量级进程,线程是程序执行的最小单位。

  • 一个程序至少一个进程,一个进程至少一个线程。

  • 进程有自己的独立地址空间,每启动一个进程,系统就会为它分配地址空间,建立数据表来维护代码段、堆栈

    段和数据段,这种操作非常昂贵。 而线程是共享进程中的数据的,使用相同的地址空间,因此CPU切换一个

    线程的花费远比进程要小很多,同时创建一个线程的开销也比进程要小很多。 线程之间的通信更方便,同一
    进程下的线程共享全局变量、静态变量等数据,而进程之间的通信需要以通信的方式进行。 如何处理好同步
    与互斥是编写多线程程序的难点。 多进程程序更健壮,进程有独立的地址空间,一个进程崩溃后,在保护模
    式下不会对其它进程产生影响, 而线程只是一个进程中的不同执行路径。线程有自己的堆栈和局部变量,但
    线程之间没有单独的地址空间,所以可能一个线程出现问题,进而导致整个程序出现问题

2.线程的状态及其相互转换

初始(NEW):新创建了一个线程对象,但还没有调用start()方法。

运行(RUNNABLE):处于可运行状态的线程正在JVM中执行,但它可能正在等待来自操作系统的其他资源,例
如处理器。
阻塞(BLOCKED):线程阻塞于synchronized锁,等待获取synchronized锁的状态。
等待(WAITING):Object.wait()、join()、 LockSupport.park(),进入该状态的线程需要等待其他线程做出一些特
定动作(通知或中断)。
超时等待(TIME_WAITING):Object.wait(long)、Thread.join()、LockSupport.parkNanos()、
LockSupport.parkUntil,该状态不同于WAITING,它可以在指定的时间内自行返回。
终止(TERMINATED):表示该线程已经执行完毕。

2.1创建线程的方式(上)

继承Thread,并重写父类的run方法

实现Runable接口,并实现run方法
实际开发中,选第2种:java只允许单继承 增加程序的健壮性,代码可以共享,代码跟数据独立

2.2创建线程的方式(下)

使用匿名内部类

Lambda表达式
线程池

线程阻塞Demo:
public class ThreadStateDemo {    public static void main(String[] args) throws InterruptedException {        /**         * Block         *///        Object obj = new Object();//        Thread thread = new Thread(()->{////            synchronized (obj){////                try {//                    Thread.sleep(100000000L);//                } catch (InterruptedException e) {//                    e.printStackTrace();//                }//            }////        });////        thread.start();////        Thread.sleep(2000L);////        Thread thread2 = new Thread(()->{////            synchronized (obj){////            }////        });//        thread2.start();////    }/** * waiting */        Object obj = new Object();        Thread thread = new Thread(() -> {            synchronized (obj) {                try {                    obj.wait();                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        });        thread.start();    }}
线程池开启单线程:
public class ThreadPool {    public static void main(String[] args) {        ExecutorService executorService = Executors.newSingleThreadExecutor();        executorService.execute(() -> {            System.out.println(Thread.currentThread().getName());        });    }}
相应的图示如下:

1373932-20190514232907241-280818093.png

3.线程的挂起跟恢复

​ 什么是挂起线程? 线程的挂起操作实质上就是使线程进入“非可执行”状态下,在这个状态下CPU不会分给线程

时间片,进入这个状态可以用来暂停一个线程的运行。 在线程挂起后,可以通过重新唤醒线程来使之恢复运

3.1 为什么要挂起线程?

​ cpu分配的时间片非常短、同时也非常珍贵。避免资源的浪费。

如何挂起线程?

  • 被废弃的方法 thread.suspend() 该方法不会释放线程所占用的资源。如果使用该方法将某个线程挂起,则可

    能会使其他等待资源的线程死锁 thread.resume() 方法本身并无问题,但是不能独立于suspend()方法存在

  • 可以使用的方法 wait() 暂停执行、放弃已经获得的锁、进入等待状态

  • notify() 随机唤醒一个在等待锁的线程

  • notifyAll() 唤醒所有在等待锁的线程,自行抢占cpu资源

被废弃的相关挂起Demo:

/** * 挂起操作的Demo */public class SuspendDemo implements Runnable{    @Override    public void run() {        System.out.println(Thread.currentThread().getName()+"进入Run()方法,准备调用SusPend");        Thread.currentThread().suspend(); //执行挂起        System.out.println(Thread.currentThread().getName()+"进入Run()方法,调用SusPend结束");    }    public static void main(String[] args) throws InterruptedException {        Thread thread = new Thread(new SuspendDemo());        thread.start();        Thread.sleep(3000L);        thread.resume(); //执行恢复    }}

这里要注意的是挂起的操作是不安全的,被废弃也是因为因为他容易造成长时间阻塞:

这里阻塞的原因是因为他在挂起前就进行来了唤醒的操作,导致后来的线程一直挂起(未睡眠导致唤醒的代码提前于挂起执行了)

** * suspend死锁演示 */public class DeadDemo implements Runnable{    private static final Object object =new Object();    @Override    public void run() {        //持有资源        synchronized (object){            System.out.println(Thread.currentThread().getName()+"占用资源");            Thread.currentThread().suspend();        }        System.out.println(Thread.currentThread().getName()+"释放资源");    }    public static void main(String[] args) throws InterruptedException {        Thread thread = new Thread(new DeadDemo(),"对比线程");        thread.start();        thread.sleep(1000L);        thread.resume();        Thread deadThread = new Thread(new DeadDemo(),"死锁线程");        deadThread.start();//        deadThread.sleep(3000L);        deadThread.resume();    }}

使用推荐的wait和notify方法操作:

package xianchengxuexi.chapter02.hang;import com.sun.jndi.toolkit.ctx.StringHeadTail;/** * 等待方法 */public class WaitDemo implements Runnable {    private static Object object =  new Object();    private static Object waitObj = new Object();    @Override    public void run() {        //持有资源        //锁住的和wait()的需要时同一个对象        synchronized (waitObj){            System.out.println(Thread.currentThread().getName()+"占用资源");            try {                waitObj.wait();//这个会释放锁            } catch (InterruptedException e) {                e.printStackTrace();            }        }        System.out.println(Thread.currentThread().getName()+"释放资源");    }    public static void main(String[] args) throws InterruptedException {        Thread thread = new Thread(new WaitDemo(),"对比线程");        thread.start();        Thread thread2 = new Thread(new DeadDemo(),"对比线程2");        thread2.start();        thread.sleep(3000L);        synchronized (waitObj){            waitObj.notify();        }    }}
3.2 什么时候适合使用挂起线程?

我等的船还不来(等待某些未就绪的资源),我等的人还不明白。直到notify方法被调用

3.3线程的中断操作
stop() 废弃方法,开发中不要使用。因为一调用,线程就立刻停止,此时有可能引发相应的线程安全性问题
/** * 不安全的stop */public class UnSafeWithStop extends Thread {    private int a =0;    private int b =0;    @Override    public void run() {        a++;        try {            sleep(2000L);        } catch (InterruptedException e) {            e.printStackTrace();        }        b++;    }    public  void printf(){        System.out.println("a的值=======>"+a);        System.out.println("b的值=======>"+b);    }    public static void main(String[] args) throws InterruptedException {        UnSafeWithStop unSafeWithStop = new UnSafeWithStop();        unSafeWithStop.start();        Thread.sleep(1000L);        unSafeWithStop.stop();        unSafeWithStop.printf();    }}
Thread.interrupt方法
/** * 使用Interrupt终止线程 */public class InterruptDemo implements Runnable {    @Override    public void run() {        while (!Thread.currentThread().isInterrupted()){            System.out.println(Thread.currentThread().getName());        }    }    public static void main(String[] args) throws InterruptedException {        Thread thread = new Thread(new InterruptDemo());        thread.start();        thread.sleep(1000L);        thread.interrupt();    }}
自行定义一个标志,用来判断是否继续执行
/** * 自定义线程终止 */public class MyInterruptDemo implements Runnable{    private static volatile boolean FLAG = true;    @Override    public void run() {        while (FLAG){            System.out.println(Thread.currentThread().getName());        }    }    public static void main(String[] args) throws InterruptedException {        Thread thread = new Thread(new MyInterruptDemo());        thread.start();        Thread.sleep(1000L);        FLAG=false;    }}

4.线程的优先级

​ 线程的优先级告诉程序该线程的重要程度有多大。如果有大量线程都被堵塞,都在等候运行,程序会尽可能地先运行优先级的那个线程。

​ 但是,这并不表示优先级较低的线程不会运行。若线程的优先级较低,只不过表示它被准许运行的机会小一些而已。

线程的优先级设置可以为1-10的任一数值,Thread类中定义了三个线程优先级,分别是:
MIN_PRIORITY(1)、NORM_PRIORITY(5)、MAX_PRIORITY(10),

​ 一般情况下推荐使用这几个常量,不要自行设置数值。

/** * 线程优先级Demo */public class ProrityDemo {    public static void main(String[] args) {        Thread thread = new Thread(() -> {            while (true){                System.out.println(Thread.currentThread().getName());            }        },"线程1");        Thread thread2 = new Thread(() -> {            while (true){                System.out.println(Thread.currentThread().getName());            }        },"线程2");        thread.setPriority(Thread.MIN_PRIORITY);        thread2.setPriority(Thread.MAX_PRIORITY);        thread.start();        thread2.start();    }}

不同平台,对线程的优先级的支持不同。 编程的时候,不要过度依赖线程优先级,如果你的程序运行是否正

确取决于你设置的优先级是否按所设置的优先级运行,那这样的程序不正确
任务:
快速处理:设置高的优先级 慢慢处理:设置低的优先级

5.守护线程

线程分类

用户线程、守护线程 守护线程:任何一个守护线程都是整个程序中所有用户线程的守护者,只要有活着的用
户线程,守护线程就活着。当JVM实例中最后一个非守护线程结束时,也随JVM一起退出
守护线程的用处:jvm垃圾清理线程
建议: 尽量少使用守护线程,因其不可控不要在守护线程里去进行读写操作、执行计算逻辑

/** * 守护线程Demo */public class DaemonThreadDemo implements Runnable{    @Override    public void run() {        while (true) {            System.out.println(Thread.currentThread().getName());            try {                Thread.sleep(1000L);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }    public static void main(String[] args) throws InterruptedException {        Thread thread = new Thread(new DaemonThreadDemo());        thread.start();        thread.setDaemon(true);        Thread.sleep(2000L);    }}

转载于:https://www.cnblogs.com/charlypage/p/10874666.html

你可能感兴趣的文章
VS2005中配置 ScriptManager,UpdatePanel,UpdateProgress 等AJAX控件 .
查看>>
使用logback实现http请求日志导入mongodb
查看>>
【 2017 Multi-University Training Contest - Team 9 && hdu 6162】Ch’s gift
查看>>
redis在php中的应用(Hash篇)
查看>>
Docker系列之Docker镜像(读书笔记)
查看>>
Scrapy 多url爬取、爬取post请求、更换代理ip、指定日志等级
查看>>
phpExcel实现excel文件导出
查看>>
Pandas中dataframe以及spark中rdd使用groupByKey进行合并
查看>>
简单字符串处理应避免使用正则表达式
查看>>
了解正则表达式操作符的优先级
查看>>
Spring框架集成FreeMarker
查看>>
用 async/await 来处理异步
查看>>
app开发-1
查看>>
在JavaScript中调用ASP.NET WebService的简单方法
查看>>
jQuery基础知识,很赞的!!!
查看>>
[SDOI 2012]Longge的问题
查看>>
简单BBS项目开始(一)
查看>>
[Codeforces 925C]Big Secret
查看>>
处理MVC中默认的Json方法返回时间的问题
查看>>
分布式技术追踪 2018年第十期
查看>>