Android多线程——关于Thread、Runnable、Callable和synchronized的理解

Thread的run()和start()

首先看下面的代码演示

public static void main(String[] args) {
    Thread newThread = new Thread(){
        @Override
        public void run() {
            super.run();
            System.out.println(Thread.currentThread().getName());
        }
    };
    newThread.run();
    newThread.start();
}

打印结果为:
main
Thread-0

如代码所示,如果直接调用run()方法,代码是在Thread对象所在的当前线程执行的。而调用start()方法,run()方法里的代码,才是在新线程里执行的。关于这个区别,可以看看Thread类中关于这样个方法的注解

* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> method of this thread.
* <p>
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* <code>start</code> method) and the other thread (which executes its
* <code>run</code> method).
* <p>
* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.

public synchronized void start() {....}
     * If this thread was constructed using a separate
     * <code>Runnable</code> run object, then that
     * <code>Runnable</code> object's <code>run</code> method is called;
     * otherwise, this method does nothing and returns.
     * <p>
     * Subclasses of <code>Thread</code> should override this method.
    
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

Thread的状态

提到这个是因为,网上的一些文章对Thread的状态,说法不一致,可能是每个人的理解不同,此处我直接查看了jdk中的源码

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;
    }

需要注意的是,有些文章会提到,Thread.start()调用后会先进入“就绪状态”,但从源码可以看出,Thread.start()的调用会让线程进入RUNNABLE状态。
另外,源码注释中提到对WAITING和TIMED_WAITING状态的区别。
WAITING状态的触发:

  • 调用Object.wait()方法,且未指定timeout参数
  • 调用Thread.join()方法,且未指定timeout参数
  • 调用LockSupport.park方法

TIMED_WAITING状态的触发:

  • 调用Thread.sleep(timeout)方法
  • 调用Object.wait(timeout)方法
  • 调用Thread.join(timeout)方法
  • 调用LockSupport.parkNanos方法
  • 调用LockSupport.parkUntil方法

ThreadLocal

在分析过Handler机制的同学,应该会在查看Looper源码时,看到这个类。

public final class Looper {
    ...
    // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
   ...
/**
 * This class provides thread-local variables.  These variables differ from
 * their normal counterparts in that each thread that accesses one (via its
 * {@code get} or {@code set} method) has its own, independently initialized
 * copy of the variable.  {@code ThreadLocal} instances are typically private
 * static fields in classes that wish to associate state with a thread (e.g.,
 * a user ID or Transaction ID).
 *
 * <p>For example, the class below generates unique identifiers local to each
 * thread.
 * A thread's id is assigned the first time it invokes {@code ThreadId.get()}
 * and remains unchanged on subsequent calls.
 * <pre>
 * import java.util.concurrent.atomic.AtomicInteger;
**/
public class ThreadLocal<T> {

从类名也可以看出,它是用来存储一个线程对象的本地化数据的。具体来说,就是在线程的整个执行过程中,都有可能用到的一些数据,通常也可以称之为上下文(Context),它是一种状态,可以是用户信息,任务信息之类的。因为在线程任务的执行过程中可能会调用到很多方法,有些方法还是层层调用,如果这些方法中要用到这些数据,除了将数据作为参数传进去之外,从ThreadLocal中读取和保存数据,就是java提供的一种方式。
看看它在Looper中的使用

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

通过get()来读取数据,set()方法来保存数据。
实际上,可以把ThreadLocal看成一个全局的Map<Thread,Object>,每个线程获取ThreadLocal变量是,总是使用Thread对象本身作为key。

Object threadLocalValue = threadLocalMap.get(Thread.currentThread());

因此,ThreadLocal相当于给每个线程都开辟了一个独立的存储空间,各个线程的ThreadLocal关联的实例互不干扰。另外,相比于直接在Thread中直接定义成员变量,这样的机制,减少了数据实例和Thread对象的耦合性。
特别注意ThreadLocal一定要在线程任务执行完毕时清除,这是因为当前线程执行完相关代码后,很可能会被重新放入线程池,如果ThreadLocal没有被清楚,该线程执行其他代码时,会把之前执行任务的状态带进去。

Thread和Runnable

在java中,一般实现创建线程执行任务的方法有两种,一种是直接继承Thread类,另一种是实现Runnable接口。区别在于:

  • java是单继承,但可以实现多个接口。所以从类的扩展来看,实现Runnable接口会比继承Thread类,更灵活。
  • Runnable只是一个接口,它本身并不具备创建线程执行任务的功能。它只是定义了一个可执行的任务。实际上,任务的执行需要Thread调用Runnable定义的run方法。
    上面THread类中默认实现的run()方法,显示了两者的关系,其中的target就是Runnable对象
/* What will be run. */
    private Runnable target;

Runnable和Callable

Callable和Runnable都是用来定义可异步执行的任务的接口,Runnable是JDK1.0就有的API,Callable是JDK1.5增加的API。两者的区别在于:

  • Callable的call()方法有返回值并且可以抛出异常,而Runnable的run()方法不具备这些特征。
  • 执行Callable任务,可以拿到一个Future对象,表示异步执行的结果。通过Future对象可以了解任务执行情况,可取消任务的执行,也可以获得执行的结果。
  • Thread类只支持执行Runnable接口,不支持执行Callable接口

FutureTask

FutureTask类实现了RunnableFuture<T>接口,而RunnbleFuture<T>接口继承了Runnable接口和Future<T>接口,也就是说FutureTask<T>类是同时实现了Runnable接口和Future<T>接口。所以它既能当做Runnable被线程执行,又能作为Future<T>得到Callable<T>的返回值。FutureTask还可以让调用者知道任务什么时候执行完,并获得线程执行完成后返回的结果。

public class FutureTask<V> implements RunnableFuture<V>{
  public FutureTask(Callable<V> callable) {
  }
  public FutureTask(Runnable runnable, V result) {
  }
}

public interface RunnableFuture<V> extends Runnable, Future<V> {
    void run();
}

下面是一个结合Callable、Future和FutureTask的常见用法

executorService = new ScheduledThreadPoolExecutor(5);
        Callable<String> task = new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName());
                System.out.println("callable is running");
                return "callable is done";
            }
        };
        /**
         * 用法一
         */
//        Future future = executorService.submit(task);
//        executorService.shutdown();
//        future.get();
        /**
         * 用法二
         */
        FutureTask futureTask = new FutureTask(task);
        executorService.submit(futureTask);
        executorService.shutdown();
        /**
         * 用法三
         */
//        new Thread(futureTask).start();

        System.out.println(Thread.currentThread().getName());
        System.out.println("main is running");
        try {
            System.out.println(futureTask.get());
            System.out.println("main get result");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

synchronized的理解

我们通常用到synchronized关键字是这样

public void testSynchronized(){
        synchronized(this){
            System.out.println("test is start");
            try {
                Thread.sleep(2000);
                System.out.println("test is over");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

或者是这样

public synchronized void testSynchronized(){
        System.out.println("test is start");
        try {
            Thread.sleep(2000);
            System.out.println("test is over");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

也就是说,synchronized既可以加在一段代码上,也可以加在方法上。看上去像是第一种锁的是一个对象,而第二种锁的是方法里的代码。但实质上并不是这样。

synchronized锁住的是括号里的对象,而不是代码。对于非static的synchronized方法,锁的就是对象本身也就是this。synchronized(this)以及非static的synchronized方法,只能防止多个线程执行同一个对象的同步代码段。
当synchronized锁住一个对象后,别的线程如果也想拿到这个对象的锁,就必须等待这个线程执行完成释放锁,才能再次给对象加锁,这样才达到线程同步的目的。即使两个不同的代码段,都要锁同一个对象,那么这两个代码段也不能在多线程环境下同时运行。

再看下下面的代码

public void testSynchronized(){
        synchronized(Account.class){
            System.out.println("test is start");
            try {
                Thread.sleep(2000);
                System.out.println("test is over");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
......
......
for (int i = 0;i < 3;i++){
            Account account = new Account();
            Thread thread = new Thread(){
                @Override
                public void run() {
                    super.run();
                    account.testSynchronized();
                }
            };
            thread.start();
        }

代码中,每个子线程中,执行的都是不同的Account对象的testSynchronized方法。那么要让testSynchronized方法不被多线程同时执行,有两种方式可以实现:

  • 如代码所示,用synchronized(Account.class),实现了全局锁的效果,锁住了代码段。
  • 也可以定义为静态方法,静态方法可以直接用类名加方法名调用,方法内无法使用this。所以锁的不是this对象,而是类的Class对象。static synchronized修饰的方法也相当于全局锁,锁住了方法内的代码。

本文参考
https://www.cnblogs.com/marsitman/p/11228684.html
https://www.liaoxuefeng.com/wiki/1252599548343744/1306581251653666

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

推荐阅读更多精彩内容

  • 进程和线程 进程 所有运行中的任务通常对应一个进程,当一个程序进入内存运行时,即变成一个进程.进程是处于运行过程中...
    胜浩_ae28阅读 5,031评论 0 23
  •   一个任务通常就是一个程序,每个运行中的程序就是一个进程。当一个程序运行时,内部可能包含了多个顺序执行流,每个顺...
    OmaiMoon阅读 1,629评论 0 12
  • 该文章转自:http://blog.csdn.net/evankaka/article/details/44153...
    加来依蓝阅读 7,257评论 3 87
  • 一.线程与进程相关 1.进程   定义:进程是具有独立功能的程序关于某个数据集合上的一次运行活动,进程是操作系统分...
    Geeks_Liu阅读 1,641评论 2 4
  • 早就想买个心率手环督促自己锻炼,但一直在选择什么牌子和心率功能是否鸡肋这两个事上纠结。 直到前几天,每天负责叫我起...
    一只奇葩阅读 594评论 0 0