Java 多线程——原理概述

2020-06-23  本文已影响0人  BitterOutsider

为什么需要多线程?

什么是Thread

Java线程模型 & 开启一个新线程

for (int i = 0; i < 3; i++) {
    new Thread(new Runnable() {
        @Override
            public void run() {
                // do some thing
            }
     }).start();
}
public class Main {
    static boolean initSignal = false;

    private static void init() {
        // 初始化操作
    }

    public static void main(String[] args) throws InterruptedException {
        new Thread(()->{
           init();
           initSignal=true;
        }).start();

        while (true){
            if(initSignal){
                //如果初始化完成,则做接下来的任务
            }else {
                Thread.sleep(500);
            }
        }
    }
}

如何解决线程自身存在的副本导致可能发生的错误呢?java引入了一个关键词volatile,当你把一个变量声明成一个volatile时,所有线程对共享变量的修改会立刻写回主内存,从变量读取会直接读取主内存 。换句话说,读写都是最新的。这叫做可见性,值得注意的时,可见性并非原子性。volatile也会禁⽌指令重排。有同步操作(synchronized/Lock/AtomicInteger,详情见Java 多线程——线程安全、线程池初步)的时候⽆需volatile,同步操作自带原子性和可见性。

volatile static boolean init = false;

多线程问题的来源

class Main {
    private static int num = 0;
    public static void main(String[] args) {
        new Thread(Main::addOne).start();
        new Thread(Main::addOne).start();
        new Thread(Main::addOne).start();
    }
    public static void addOne(){
        for (int i = 0; i < 10000; i++) {
            num++;
            System.out.println(num);
        }
    }
}

线程的生命周期

     * <ul>
     * <li>{@link #NEW}<br>
     *     一个线程还没有开始执行,刚new出来。
     *     A thread that has not yet started is in this state.
     *     </li>
     * <li>{@link #RUNNABLE}<br>
     *     一个线程正在Java虚拟机中被执行
     *     A thread executing in the Java virtual machine is in this state.
     *     </li>
     * <li>{@link #BLOCKED}<br>
     *     一个线程正在等待一个monitor lock。
     *     我们使用synchronized块锁住一个对象,有多个线程没有拿到锁,进入阻塞状态。
     *     A thread that is blocked waiting for a monitor lock
     *     is in this state.
     *     </li>
     * <li>{@link #WAITING}<br>
     *     处于wait状态的线程(调用了wait方法)
     *     A thread that is waiting indefinitely for another thread to
     *     perform a particular action is in this state.
     *     </li>
     * <li>{@link #TIMED_WAITING}<br>
     *     处于wait状态的线程(调用了wait方法),有时间限制。
     *     A thread that is waiting for another thread to perform an action
     *     for up to a specified waiting time is in this state.
     *     </li>
     * <li>{@link #TERMINATED}<br>
     *     一个线程退出了的状态。
     *     A thread that has exited is in this state.
     *     </li>
     * </ul>

适合使用多线程的场合

本文完。

上一篇 下一篇

猜你喜欢

热点阅读