Thread 随笔
今天要写一个简单的多线程测试 ArrayList 的线程不安全属性, 突然发现 Thread 需要再复习下了.
了解下:
Thread 是计算机运算的最小单位. 每个线程有独立的运算栈和程序计数器.
Thread 分为五个状态, 创建(new), 就绪(runnable), 执行(running), blocking(阻塞[等待/同步/其他]), 死亡(dead).
多次启动一个线程是非法的, 尤其是当线程已经结束执行时, 不能再重新启动.
普通新建线程一般三种方式, 一是继承 Thread 重写 run() 方法, 一是实现 Runnable 接口, 一是直接创建 Runnable 匿名内部类. 日常测试第三种写起来最方便.
Thread 中 start() 和 run() 方法是常常拿来做比较的:
start() 方法:
/** * Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. * The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method). * It is never legal to start a thread more than once. * In particular, a thread may not be restarted once it has completed execution.*/
Thread 的 start() 方法用来启动线程, 会额外的创建一个新的线程, 该方法会在内部调用 Runnable 接口的 run() 方法, 以在新的线程中执行 run() 方法中指定的代码.
大概步骤: 01 创建一个新线程 02 线程状态从 new 移动到 runnable 03 当线程有机会执行时, run() 方法中的代码执行 04 run() 方法执行完毕, 此线程 dead.
run() 方法:
/** * If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; * otherwise, this method does nothing and returns. * Subclasses of Thread should override this method. */
Thread 的 run() 方法用来执行 run() 方法中的代码, 直接调用 run() 方法, 程序中依然只有主线程这一条线程, 不会创建新的线程, 所有任务顺序执行, 等 run() 方法体执行完毕之后才可以继续执行下面的代码(达不到我们平时对多线程的需求).
构造方法: (最常用的两种)
public Thread(Runnable target) { init(null, target, "Thread-" + nextThreadNum(), 0); } public Thread(ThreadGroup group, Runnable target, String name) { init(group, target, name, 0); }
Thread 深入探索, 回头再说.