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 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.
public synchronized void start() {....}
* 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.
@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:
*
* - {@link Object#wait() Object.wait} with no timeout
* - {@link #join() Thread.join} with no timeout
* - {@link LockSupport#park() LockSupport.park}
*
*
* A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called Object.wait()
* on an object is waiting for another thread to call
* Object.notify() or Object.notifyAll() on
* that object. A thread that has called Thread.join()
* 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:
*
* - {@link #sleep Thread.sleep}
* - {@link Object#wait(long) Object.wait} with timeout
* - {@link #join(long) Thread.join} with timeout
* - {@link LockSupport#parkNanos LockSupport.parkNanos}
* - {@link LockSupport#parkUntil LockSupport.parkUntil}
*
*/
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 sThreadLocal = new ThreadLocal();
...
/**
* 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).
*
* 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.
*
* import java.util.concurrent.atomic.AtomicInteger;
**/
public class ThreadLocal {
从类名也可以看出,它是用来存储一个线程对象的本地化数据的。具体来说,就是在线程的整个执行过程中,都有可能用到的一些数据,通常也可以称之为上下文(Context),它是一种状态,可以是用户信息,任务信息之类的。因为在线程任务的执行过程中可能会调用到很多方法,有些方法还是层层调用,如果这些方法中要用到这些数据,除了将数据作为参数传进去之外,从ThreadLocal中读取和保存数据,就是java提供的一种方式。
看看它在Looper中的使用
static final ThreadLocal sThreadLocal = new ThreadLocal();
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
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
public class FutureTask implements RunnableFuture{
public FutureTask(Callable callable) {
}
public FutureTask(Runnable runnable, V result) {
}
}
public interface RunnableFuture extends Runnable, Future {
void run();
}
下面是一个结合Callable、Future和FutureTask的常见用法
executorService = new ScheduledThreadPoolExecutor(5);
Callable task = new Callable() {
@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