Thread start()方法和run()方法的区别
Thread start() 方法?,是一個線程開始的方法
Thread run() 方法 ,就是一個普通的方法,可以理解為main方法里面的一個普通的方法
?下面寫一個demo 理解下
Thread thread = new Thread("other"){@Overridepublic void run() {super.run();String threadName = Thread.currentThread().getName();long id = Thread.currentThread().getId();Log.e("------hxm","threadName = " + threadName + ", id = " + id);}};thread.start();
Thread start() 打印的結果為:------hxm: threadName = other, id = 1286
Thread thread = new Thread("other"){@Overridepublic void run() {super.run();String threadName = Thread.currentThread().getName();long id = Thread.currentThread().getId();Log.e("------hxm","threadName = " + threadName + ", id = " + id);}};thread.run();
Thread run() 打印的結果為:------hxm: threadName = main, id = 2
?
上面的對比不難發(fā)現(xiàn)?Thread start() 的線程為自己創(chuàng)建的other 它的run方法在other線程,Thread run() 則是main 它的run方法在主線程(Thread.currentThread().getName() 是獲取當前線程的名字)
如果想更多的了解可以看下源碼,這里我看的是android 里面的源碼,可能存在修改
start() 方法?
public synchronized void start() {/*** This method is not invoked for the main method thread or "system"* group threads created/set up by the VM. Any new functionality added* to this method in the future may have to also be added to the VM.** A zero status value corresponds to state "NEW".*/// Android-changed: Replace unused threadStatus field with started field.// The threadStatus field is unused on Android.if (started)throw new IllegalThreadStateException();/* Notify the group that this thread is about to be started* so that it can be added to the group's list of threads* and the group's unstarted count can be decremented. */group.add(this);// Android-changed: Use field instead of local variable.// It is necessary to remember the state of this across calls to this method so that it// can throw an IllegalThreadStateException if this method is called on an already// started thread.started = false;try {// Android-changed: Use Android specific nativeCreate() method to create/start thread.// start0();nativeCreate(this, stackSize, daemon);started = true;} finally {try {if (!started) {group.threadStartFailed(this);}} catch (Throwable ignore) {/* do nothing. If start0 threw a Throwable thenit will be passed up the call stack */}}}
// Android-changed: Use Android specific nativeCreate() method to create/start thread. // start0(); nativeCreate(this, stackSize, daemon);
看了下nativeCreate 方法里面也是run方法,不過nativeCreate作用了,說了就是創(chuàng)建或者開啟一個線程的.
android 對這個地方有所修改,就是使用特有的nativeCreate() 方法,創(chuàng)建或者開啟線程.?在往下看就是native 了,這個沒有看,
?
run() 方法
直接調用的run 方法
在看target 是 什么
可以看出target 就是Runnable 對象本身.
?
?
總結
以上是生活随笔為你收集整理的Thread start()方法和run()方法的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 求一个带芷的好听的女孩名字。
- 下一篇: BigDecimal 转换为int 或者