并发编程之线程

一、并发、并行、串行

并发: 多个任务在同一时间段内同时执行,如果是单核计算机,CPU会不断地切换任务来完成并发操作

并行:多任务在同一时刻同时执行,计算机需要有多核心,每个核心独立执行一个任务,多个任务同时执行,不需要切换

串行:多任务开始执行,任务A、B、C全部执行完成后才算是结束

二、线程的定义

线程是一个轻量级的进程,是进程中的一个执行单元,是CPU的最小调度单元,一个进程中可以有N个线程

三、线程的创建(Java中是如何使用线程的)

3.1 实现Runable接口

public class Thread01 implements Runnable{

    @Override
    public void run() {
        System.out.println("当前线程为:" + Thread.currentThread().getName());
    }
}

3.2 匿名内部类实现Runable接口

public class Thread02 {

    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("使用匿名内部类,实现Runnable接口的当前线程" + Thread.currentThread().getName());
            }
        });
        thread.start();
    }
}

3.3 继承Thread对象

public class Thread03 extends Thread {


    @Override
    public void run() {
        System.out.println("继承Thread类的当前线程" + Thread.currentThread().getName());
    }
}

3.4 匿名内部类继承Thread对象

public class Thread04 {

    public static void main(String[] args) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                System.out.println("匿名内部类继承Thread的当前线程" + Thread.currentThread().getName());
            }
        };
        thread.start();
    }
}

3.5 Lambda表达式

public class Thread05 {

    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("使用lambda表达式创建当前线程:" + Thread.currentThread().getName());
        });
        thread.start();
    }
}

实现Callable接口   线程池创建(后续补充)

四、线程的启动和停止方式

线程的启动就是执行start方法,然后启动该线程。

线程停止:正常的情况下应该满足 1.停止接收新的请求 2.然后把已经接收到的请求处理完 3.停止线程

interrupt()友好的停止线程

主动停止的方式->run方法执行结束

被动停止的方式

public class Thread01 implements Runnable{

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Thread01());
        thread.start();
        Thread.sleep(2000);
        thread.interrupt();   //发送一个中断信号 中断标记变为true
    }
    @Override
    public void run() {
        // Thread.currentThread().isInterrupted() 获取中断状态
        while (!Thread.currentThread().isInterrupted()) {  
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {   // 中断标记变为false
                e.printStackTrace();  // 这里会复位
                //todo  这里的选择在于开发者  决定是否要真的中断
                Thread.currentThread().interrupt(); // 真正的中断  中断标记变为true
            }
            System.out.println("当前线程为:" + Thread.currentThread().getName());
        }
    }
}

分析:线程的中断在底层会有一个中断标记,当主线程执行interrupt(),就会向该线程发出一个中断标记,表示我要你当前线程中断了,但是真正的中断与否取决于当前线程,Thread.currentThread().isInterrupted()该方法会获取主线程发过来的中断状态并且复位,然后真正的中断操作由开发者在当前线程决定,这就是友好的线程中断方式

:TInterruptedExceptio该异常有两个功能  1. 唤醒处于阻塞状态下的线程, 2.修改中断的状态由true变为false

五、线程的生命周期

线程从start启动一个线程   到线程中的指令执行完毕后结束,即run方法结束

六、线程的状态流转

并发编程之线程_第1张图片

分析: 线程在java中分为6个状态  NEW 、RUNNABLE、WAITING、TIMED_WAITING、 BLOCKED、TERMINATED

在源码的Thread类中有这么一个状态枚举

    public enum State {
        /**
         * Thread state for a thread which has not yet started.
         */
        NEW,

        /**
         * Thread state for a runnable thread.  A thread in the runnable
         * state is executing in the Java virtual machine but it may
         * be waiting for other resources from the operating system
         * such as processor.
         */
        RUNNABLE,

        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * 
    *
  • {@link Object#wait() Object.wait} with no timeout
  • *
  • {@link #join() Thread.join} with no timeout
  • *
  • {@link LockSupport#park() LockSupport.park}
  • *
* *

A thread in the waiting state is waiting for another thread to * perform a particular action. * * For example, a thread that has called Object.wait() * on an object is waiting for another thread to call * Object.notify() or Object.notifyAll() on * that object. A thread that has called Thread.join() * is waiting for a specified thread to terminate. */ WAITING, /** * Thread state for a waiting thread with a specified waiting time. * A thread is in the timed waiting state due to calling one of * the following methods with a specified positive waiting time: *

    *
  • {@link #sleep Thread.sleep}
  • *
  • {@link Object#wait(long) Object.wait} with timeout
  • *
  • {@link #join(long) Thread.join} with timeout
  • *
  • {@link LockSupport#parkNanos LockSupport.parkNanos}
  • *
  • {@link LockSupport#parkUntil LockSupport.parkUntil}
  • *
*/ TIMED_WAITING, /** * Thread state for a terminated thread. * The thread has completed execution. */ TERMINATED; }

6.1 新建状态(NEW)

并发编程之线程_第2张图片

创建一个线程,但还未启动,为初始NEW状态

6.2 运行中(RUNNABLE)

并发编程之线程_第3张图片

增加了一个start方法 启动该线程,则该线程进入RUNNABLE状态

6.3 等待(WAITING)

并发编程之线程_第4张图片

调用wait方法让线程处于等待状态

6.4 阻塞(BLOCKED)

public class ThreadBlocked {
    synchronized public static void blocked() {
        try {
            Thread.sleep(1000000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    public static void main(String[] args) throws InterruptedException{
        Thread thread1 = new Thread(ThreadBlocked::blocked);
        Thread thread2 = new Thread(ThreadBlocked::blocked);
        thread2.start();
        thread1.start();
        System.out.println("线程状态:" + thread2.getState());
        System.out.println("线程状态:" + thread1.getState());
    }
}

并发编程之线程_第5张图片

线程2先获取到锁,线程1就处于阻塞状态

6.5 超时等待(TIMED_WAITING)

并发编程之线程_第6张图片

与等待类似,只不过限定了一个时间,超过时间就取消等待

6.6 终止状态(TERMINATED)

并发编程之线程_第7张图片

线程运行结束

七、线程的通信方式

1.共享内存。如volatile共享内存

2.消息传递。如wait/notify等待通知方式

3.管道输入/输出流。 如PipedOutputStrean、PipedInputStrean、PipedReader和PipedWriter

八、线程的安全性问题

如果多个线程在做同一件事情的时候,会造成以下的安全性问题:

1.原子性  Synchronized、AtomicXXX、Lock

2.可见性 Synchronized、volatile

3.有序性 Synchronized、volatile

你可能感兴趣的:(java,jvm,开发语言,并发编程)