Java创建多线程的4种方式 与 线程状态

线程的状态

在进行多线程编程之前,要先知道线程都有哪几种状态。

线程的状态在 java.lang.Thread.State 有定义:

/**

    * A thread state.  A thread can be in one of the following states:

    * <ul>

    * <li>{@link #NEW}<br>

    *    A thread that has not yet started is in this state.

    *    </li>

    * <li>{@link #RUNNABLE}<br>

    *    A thread executing in the Java virtual machine is in this state.

    *    </li>

    * <li>{@link #BLOCKED}<br>

    *    A thread that is blocked waiting for a monitor lock

    *    is in this state.

    *    </li>

    * <li>{@link #WAITING}<br>

    *    A thread that is waiting indefinitely for another thread to

    *    perform a particular action is in this state.

    *    </li>

    * <li>{@link #TIMED_WAITING}<br>

    *    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>

    *

    * <p>

    * A thread can be in only one state at a given point in time.

    * These states are virtual machine states which do not reflect

    * any operating system thread states.

    *

    * @since  1.5

    * @see #getState

    */

    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:

        * <ul>

        *  <li>{@link Object#wait() Object.wait} with no timeout</li>

        *  <li>{@link #join() Thread.join} with no timeout</li>

        *  <li>{@link LockSupport#park() LockSupport.park}</li>

        * </ul>

        *

        * <p>A thread in the waiting state is waiting for another thread to

        * perform a particular action.

        *

        * For example, a thread that has called <tt>Object.wait()</tt>

        * on an object is waiting for another thread to call

        * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on

        * that object. A thread that has called <tt>Thread.join()</tt>

        * 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:

        * <ul>

        *  <li>{@link #sleep Thread.sleep}</li>

        *  <li>{@link Object#wait(long) Object.wait} with timeout</li>

        *  <li>{@link #join(long) Thread.join} with timeout</li>

        *  <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>

        *  <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>

        * </ul>

        */

        TIMED_WAITING,

        /**

        * Thread state for a terminated thread.

        * The thread has completed execution.

        */

        TERMINATED;

    }

<li>{@link #NEW}<br>

*    A thread that has not yet started is in this state.

*    </li>

  创建后尚未启动的线程处于这种状态

* <li>{@link #RUNNABLE}<br>

*    A thread executing in the Java virtual machine is in this state.

*    </li>

  Runable包括了操作系统线程状态的Running和Ready,也就是处于此状态的线程有可能正在执行,也有可能正在等待着CPU为它分配执行时间。

* <li>{@link #BLOCKED}<br>

*    A thread that is blocked waiting for a monitor lock

*    is in this state.

*    </li>

  线程被阻塞了,“阻塞状态”与”等待状态“的区别是:”阻塞状态“在等待着获取到一个排他锁,这个时间将在另外一个线程放弃这个锁的时候发生;而”等待状态“则是在等待一段时间或者唤醒动作的发生。在程序等待进入同步区域的时候,线程将进入这种状态。

* <li>{@link #WAITING}<br>

*    A thread that is waiting indefinitely for another thread to

*    perform a particular action is in this state.

*    </li>

  处于这种状态的线程不会被分配CPU执行时间。

  等待状态又分为无限期等待和有限期等待,WAITING 为无限期等待

  处于无限期等待的线程需要被其他线程显示地唤醒,没有设置Timeout参数的Object.wait()、没有设置Timeout参数的Thread.join()方法都会使线程进入无限期等待状态;

线程处于WAITING状态的场景。

调用Object对象的wait方法,但没有指定超时值。

调用Thread对象的join方法,但没有指定超时值。

调用LockSupport对象的park方法。

* <li>{@link #TIMED_WAITING}<br>

*    A thread that is waiting for another thread to perform an action

*    for up to a specified waiting time is in this state.

*    </li>

  当处于一个给定的等待时间时候,线程处于这种状态 TIMED_WAITING

  有限期等待状态无须等待被其他线程显示地唤醒,在一定时间之后它们会由系统自动唤醒,Thread.sleep()、设置了Timeout参数的Object.wait()、设置了Timeout参数的Thread.join()方法都会使线程进入有限期等待状态。

线程处于TIMED_WAITING状态的场景。

调用Thread.sleep方法。

调用Object对象的wait方法,指定超时值。

调用Thread对象的join方法,指定超时值。

调用LockSupport对象的parkNanos方法。

调用LockSupport对象的parkUntil方法。

* <li>{@link #TERMINATED}<br>

*    A thread that has exited is in this state.

*    </li>

  已终止线程的线程状态,线程已经结束执行。


线程状态间的切换

既然有那么多的线程状态,它们之间的状态转换如下图所示


线程间同步的方法

线程有4中同步方法,分别为wait()、sleep()、notify()和notifyAll()。

wait():使线程处于一种等待状态,释放所持有的对象锁。

sleep():使一个正在运行的线程处于睡眠状态,是一个静态方法,调用它时要捕获InterruptedException异常,不释放对象锁。

notify():唤醒一个正在等待状态的线程。注意调用此方法时,并不能确切知道唤醒的是哪一个等待状态的线程,是由JVM来决定唤醒哪个线程,不是由线程优先级决定的。

notifyAll():唤醒所有等待状态的线程,注意并不是给所有唤醒线程一个对象锁,而是让它们竞争。


Java 创建线程的4种方式 :

继承Thread类创建多线程

实现Runnable接口创建多线程

实现Callable接口通过FutureTask包装器来创建Thread多线程

使用ExecutorService、Callable、Future实现有返回结果的线程。


继承Thread类创建多线程

代码如下:继承Thread类

package com.dazhi.thread.multithread;

/**

 * 多线程创建,继承

 * @author dazhi

 */

public class MyThread extends Thread{

    @Override

    public void run() {

        for (int i=0; i<10; i++) {

            System.out.println(Thread.currentThread().getName() +":"+ i);

        }

    }

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

        MyThread thread1 = new MyThread();

        MyThread thread2 = new MyThread();

        MyThread thread3 = new MyThread();

        thread1.start();

        thread2.start();

        thread3.start();

    }

}


实现Runnable接口创建多线程

实现Runnable接口

package com.dazhi.thread.multithread;

/**

 * 多线程创建, 实现Runnable

 * @author dazhi

 */

public class MyRunnable implements Runnable {

    @Override

    public void run() {

        for (int i=0; i<10; i++) {

            System.out.println(Thread.currentThread().getName() +":"+ i);

        }

    }

    public static void main(String[] args) {

        MyRunnable myRunnable = new MyRunnable();

        Thread thread1 = new Thread(myRunnable, "thread1");

        Thread thread2 = new Thread(myRunnable, "thread2");

        Thread thread3 = new Thread(myRunnable, "thread3");

        thread1.start();

        thread2.start();

        thread3.start();

    }

}


实现Callable接口通过FutureTask包装器来创建Thread多线程

实现Callable

package thread.multi;

import java.util.concurrent.Callable;

import java.util.concurrent.FutureTask;

/**

* Created by szh on 2020/6/15.

*

* @author szh

*/

public class CallableThread implements Callable<String> {

    @Override

    public String call() throws Exception {

        Thread.sleep(10 * 1000);

        return "Just do it";

    }

    public static void main(String[] args) throws Exception {

        CallableThread callableThread = new CallableThread();

        FutureTask<String> stringFuture = new FutureTask<String>(callableThread);

        Thread a = new Thread(stringFuture);

        a.start();

        System.out.println(stringFuture.get());

    }

}

// 运行结果

Just do it

注意  get 会阻塞线程的运行,直到得到返回结果!!




使用ExecutorService、Callable、Future实现有返回结果的线程。


package com.dazhi.thread.multithread;

import java.util.concurrent.*;

/**

 * 多线程创建, ExecutorService + Callable + Future

 * @author dazhi

 */

public class MyExecutors {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        // 不提倡的方式创建线程池方式。为了方便就这样写了

        ExecutorService executorService = Executors.newFixedThreadPool(5);

        Future<Integer> submit = executorService.submit(new Callable<Integer>() {

            @Override

            public Integer call() throws Exception {

                return 1234;

            }

        });

        executorService.shutdown();

        System.out.println(submit.get());

    }

}

// 运行结果

1234

Process finished with exit code 0

// 不提倡创建线程池的原因

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