Java线程

一、创建线程

1.方式一:直接使用 Thread

@Slf4j
public class MyThread1 {

    public static void main(String[] args) {
        new Thread(()->{
            log.debug("t1 thread running");
        },"t1").start();
        log.debug("main thread running");
    }
}
20:11:09.740 [main] DEBUG juc.thread.MyThread1 - main thread running
20:11:09.740 [t1] DEBUG juc.thread.MyThread1 - t1 thread running

2.方式二:使用 Runnable 配合 Thread

@Slf4j
public class MyThread2 {
    public static void main(String[] args) {
        Runnable runnable = ()->log.debug("t2 thread running");
        Thread thread = new Thread(runnable,"t2");
        thread.start();
        log.debug("main thread running");
    }
}
10:15:20.385 [t2] DEBUG juc.thread.MyThread2 - t2 thread running
10:15:20.385 [main] DEBUG juc.thread.MyThread2 - main thread running

3.方式三:FutureTask 配合 Thread

FutureTask 能够接收 Callable 类型的参数,用来处理有返回结果的情况

@Slf4j
public class MyThread3 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> futureTask = new FutureTask<>(()->{
            log.debug("t3 thread running");
            Thread.sleep(3000);
            return 3;
        });

        Thread thread = new Thread(futureTask,"t3");
        thread.start();

        //阻塞等待结果返回
        Integer integer = futureTask.get();
        log.debug("t3 result is"+integer);
    }
}
10:54:23.627 [t3] DEBUG juc.thread.MyThread3 - t3 thread running
10:54:26.631 [main] DEBUG juc.thread.MyThread3 - t3 result is3

二、线程运行原理

JVM 中由堆、栈、方法区所组成,其中栈内存是给线程用的,每个线程启动后,虚拟机就会为其分配一块栈内存:

  • 每个栈由多个栈帧(Frame)组成,对应着每次方法调用时所占用的内存
  • 每个线程只能有一个活动栈帧,对应着当前正在执行的那个方法

三、线程上下文切换

因为以下一些原因导致 cpu 不再执行当前的线程,转而执行另一个线程的代码;

  • 线程的 cpu 时间片用完
  • 垃圾回收
  • 有更高优先级的线程需要运行
  • 线程自己调用了 sleep、yield、wait、join、park、synchronized、lock 等方法

当 Context Switch 发生时,需要由操作系统保存当前线程的状态,并恢复另一个线程的状态,Java 中对应的概念就是程序计数器(Program Counter Register),它的作用是记住下一条 jvm 指令的执行地址,是线程私有的

  • 状态包括程序计数器、虚拟机栈中每个栈帧的信息,如局部变量、操作数栈、返回地址等
  • Context Switch 频繁发生会影响性能(线程数超过了CPU核心)

四、sleep 与 yield

sleep

  • 1.调用 sleep 会让当前线程从 Running 进入 Timed Waiting 状态(阻塞)
  • 2.其它线程可以使用 interrupt 方法打断正在睡眠的线程,这时 sleep 方法会抛出 InterruptedException
  • 3.睡眠结束后的线程未必会立刻得到执行
  • 4.建议用 TimeUnit 的 sleep 代替 Thread 的 sleep 来获得更好的可读性
@Slf4j
public class MyThread4 {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            log.debug("enter sleep");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                log.debug("wake up");
                e.printStackTrace();
            }
        });
        thread.start();
        Thread.sleep(1000);
        log.debug("interrupt");
        thread.interrupt();
    }
}
17:04:34.423 [Thread-0] DEBUG juc.thread.MyThread4 - enter sleep
17:04:35.419 [main] DEBUG juc.thread.MyThread4 - interrupt
17:04:35.420 [Thread-0] DEBUG juc.thread.MyThread4 - wake up
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at juc.thread.MyThread4.lambda$main$0(MyThread4.java:20)
    at java.lang.Thread.run(Thread.java:748)

yield

  • 1.调用 yield 会让当前线程从 Running 进入 Runnable 就绪状态,然后调度执行其它线程
  • 2.具体的实现依赖于操作系统的任务调度器

五、线程优先级

线程优先级会提示(hint)调度器优先调度该线程,但它仅仅是一个提示,调度器可以忽略它
如果 cpu 比较忙,那么优先级高的线程会获得更多的时间片,但 cpu 闲时,优先级几乎没作用

六、join

@Slf4j
public class TestJoin {
    static int r = 0;
    public static void main(String[] args) throws InterruptedException {
        test1();
    }
    private static void test1() throws InterruptedException {
        log.debug("开始");
        Thread t1 = new Thread(() -> {
            log.debug("开始");
            sleep(1);
            log.debug("结束");
            r = 10;
        },"t1");
        t1.start();
        t1.join();
        log.debug("结果为:{}", r);
        log.debug("结束");
    }
}

让线程按顺序执行,调用join方法,主线程会让t1线程加入到当前线程,执行完才会继续往下执行。

@Slf4j
public class TestJoin {
    static int r = 0;
    static int r1 = 0;
    static int r2 = 0;

    public static void main(String[] args) throws InterruptedException {
        test2();
    }

    private static void test2() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            sleep(1);
            r1 = 10;
        });
        Thread t2 = new Thread(() -> {
            sleep(2);
            r2 = 20;
        });
        t1.start();
        t2.start();
        long start = System.currentTimeMillis();
        log.debug("join begin");
        t2.join();
        log.debug("t2 join end");
        t1.join();
        log.debug("t1 join end");
        long end = System.currentTimeMillis(); 
        //17:46:36.413 [main] DEBUG juc.thread.TestJoin - r1: 10 r2: 20 cost: 2003
        log.debug("r1: {} r2: {} cost: {}", r1, r2, end - start);
    }
}

第一个 join:等待 t1 时, t2 并没有停止, 而在运行
第二个 join:1s 后, 执行到此, t2 也运行了 1s, 因此也只需再等待 1s

有时效的 join

@Slf4j
public class TestJoin {
    static int r = 0;
    static int r1 = 0;
    static int r2 = 0;

    public static void main(String[] args) throws InterruptedException {
        test3();
    }

    public static void test3() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            sleep(2);
            r1 = 10;
        });

        long start = System.currentTimeMillis();
        t1.start();

        // 线程执行结束会导致 join 结束
        log.debug("join begin");
        //17:52:32.167 [main] DEBUG juc.thread.TestJoin - r1: 0 r2: 0 cost: 1510
        //没等够时间,没赋值成功
        t1.join(1500);

        //17:50:56.836 [main] DEBUG juc.thread.TestJoin - r1: 10 r2: 0 cost: 2003
        //只需要等2s 给了3s 也只会等2s
        //t1.join(3000);
        long end = System.currentTimeMillis();

        log.debug("r1: {} r2: {} cost: {}", r1, r2, end - start);
    }
}

七、interrupt 方法

1.打断 sleep,wait,join 的线程

阻塞状态的下的线程,如果被打断,打断标志位会被清空
sleep,wait,join 这几个方法都会让线程进入阻塞状态,打断标志位清空

@Slf4j
public class Test1 {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            log.debug("sleep...");
            try {
                //sleep, wait, join 会在被打断之后把打断标志位清空
                Thread.sleep(5000); //
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t1");

        t1.start();
        Thread.sleep(1000);
        log.debug("interrupt");
        t1.interrupt();
        //false
        log.debug("打断标记:{}", t1.isInterrupted());
    }
}

线程被打断,捕获到异常,就会将标志位置为false

2.打断正常运行的线程

打断正常运行的线程, 被打断,不会清空打断状态
正常运行的线程被打断之后,不会终止运行,只是收到了一个被打断的标识,如果需要根据被打断做处理,需要手动写代码处理,被打断的线程自己决定是要继续运行还是停止运行。

@Slf4j
public class Test1 {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            while(true) {
                boolean interrupted = Thread.currentThread().isInterrupted();
                if(interrupted) {
                    log.debug("被打断了, 退出循环");
                    break;
                }
            }
        }, "t1");
        t1.start();
        Thread.sleep(1000);
        log.debug("interrupt");
        t1.interrupt();
    }
}

两阶段终止

image.png
@Slf4j
public class TestInterrupt {

    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTerminate twoPhaseTerminate = new TwoPhaseTerminate();
        twoPhaseTerminate.start();
        Thread.sleep(4000);
        twoPhaseTerminate.stop();
    }
}

@Slf4j
class TwoPhaseTerminate {

    private Thread monitorThread;

    /**
     * 启动线程
     */
    public void start() {
        monitorThread = new Thread(() -> {
            while (true) {
                Thread current = Thread.currentThread();
                // 是否被打断
                if (current.isInterrupted()) {
                    log.debug("料理后事");
                    break;
                }
                try {
                    Thread.sleep(1000);
                    log.debug("执行监控记录");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    //重置清除标志
                    current.interrupt();
                }
            }
        }, "monitor");
        monitorThread.start();
    }

    /**
     * 停止线程
     */
    public void stop() {
        monitorThread.interrupt();
    }
}
18:56:14.235 [monitor] DEBUG juc.thread.TwoPhaseTerminate - 执行监控记录
18:56:15.243 [monitor] DEBUG juc.thread.TwoPhaseTerminate - 执行监控记录
18:56:16.245 [monitor] DEBUG juc.thread.TwoPhaseTerminate - 执行监控记录
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at juc.thread.TwoPhaseTerminate.lambda$start$0(TestInterrupt.java:42)
    at java.lang.Thread.run(Thread.java:748)
18:56:17.235 [monitor] DEBUG juc.thread.TwoPhaseTerminate - 料理后事

isInterrupted: 判断是否被打断,不会清除打断标记
interruptted: 判断当前线程是否被打断,会清除打断标记

3.打断 park 线程

调用park方法之后不会往下执行。一直阻塞

@Slf4j
public class ParkTest {

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            log.debug("park...");
            LockSupport.park();
            log.debug("unpark...");
            log.debug("打断状态:{}", Thread.currentThread().isInterrupted());
        }, "t1");
        t1.start();
    }
}
19:03:51.383 [t1] DEBUG juc.thread.ParkTest - park...

被打断之后,标志位为true

@Slf4j
public class ParkTest {

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            log.debug("park...");
            LockSupport.park();
            log.debug("unpark...");
            log.debug("打断状态:{}", Thread.currentThread().isInterrupted());
        }, "t1");
        t1.start();
        Thread.sleep(1000);
        t1.interrupt();
    }
}
19:05:17.069 [t1] DEBUG juc.thread.ParkTest - park...
19:05:18.069 [t1] DEBUG juc.thread.ParkTest - unpark...
19:05:18.070 [t1] DEBUG juc.thread.ParkTest - 打断状态:true

当被打断了,标志位为true,会让park失效,再次park的时候会失效,不会阻塞:

@Slf4j
public class ParkTest {

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            log.debug("park...");
            LockSupport.park();
            log.debug("unpark...");
            //true
            log.debug("打断状态:{}", Thread.currentThread().isInterrupted());
            LockSupport.park();
            log.debug("unpark...");
        }, "t1");
        t1.start();
        Thread.sleep(1000);
        t1.interrupt();
    }
}
19:08:21.353 [t1] DEBUG juc.thread.ParkTest - park...
19:08:22.350 [t1] DEBUG juc.thread.ParkTest - unpark...
19:08:22.350 [t1] DEBUG juc.thread.ParkTest - 打断状态:true
19:08:22.352 [t1] DEBUG juc.thread.ParkTest - unpark...

可以调用interrupted方法,在被打断之后,标志位被清空,再park可以阻塞:

@Slf4j
public class ParkTest {

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            log.debug("park...");
            LockSupport.park();
            log.debug("unpark...");
            //true
            //log.debug("打断状态:{}", Thread.currentThread().isInterrupted());
            log.debug("打断状态:{}", Thread.interrupted());
            LockSupport.park();
            log.debug("unpark...");
        }, "t1");
        t1.start();
        Thread.sleep(1000);
        t1.interrupt();
    }
}
19:11:50.823 [t1] DEBUG juc.thread.ParkTest - park...
19:11:51.823 [t1] DEBUG juc.thread.ParkTest - unpark...
19:11:51.824 [t1] DEBUG juc.thread.ParkTest - 打断状态:true

八、主线程与守护线程

默认情况下,Java 进程需要等待所有线程都运行结束,才会结束。有一种特殊的线程叫做守护线程,只要其它非守护线程运行结束了,即使守护线程的代码没有执行完,也会强制结束。

@Slf4j
public class Test5 {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    break;
                }
            }
            log.debug("t1结束");
        }, "t1");
        t1.setDaemon(true);
        t1.start();

        Thread.sleep(1000);
        log.debug("main线程结束");
    }
}
19:25:06.046 [main] DEBUG juc.thread.Test5 - main线程结束

垃圾回收器线程就是一种守护线程
Tomcat 中的 Acceptor 和 Poller 线程都是守护线程,所以 Tomcat 接收到 shutdown 命令后,不会等待它们处理完当前请求

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,063评论 6 510
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,805评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,403评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,110评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,130评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,877评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,533评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,429评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,947评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,078评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,204评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,894评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,546评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,086评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,195评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,519评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,198评论 2 357

推荐阅读更多精彩内容

  • 并发编程 Java线程 创建和运行线程 查看线程 线程API 线程状态 创建和运行线程 方法一,直接使用new T...
    站得高看得远阅读 270评论 1 1
  • [TOC] 4 运行原理 4.1 栈与栈帧 Java Virtual Machine Stacks (Java ...
    净土_0342阅读 260评论 0 0
  • 一、线程的状态 1.1 操作系统层面 在操作系统层面有五种状态: 【初始状态】仅是在语言层面创建了线程对象,还未与...
    我犟不过你阅读 978评论 3 9
  • 1、多线程有什么用?一个可能在很多人看来很扯淡的一个问题:我会用多线程就好了,还管它有什么用?在我看来,这个回答更...
    BlackWingXu阅读 389评论 1 3
  • 前言 参考-1参考-2参考-3-实现ABC轮流打印 进程及其作用 一个进程就是一个运行中的程序。例如:在 wind...
    luckee阅读 391评论 0 0