Thread類
引言
摳Thread類所有公有的方法和實現。
執行緒的狀態:內部列舉類State
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;
}
/**
* Returns the state of this thread.
* This method is designed for use in monitoring of the system state,
* not for synchronization control.
*
* @return this thread's state.
* @since 1.5
*/
public State getState() {
// get current thread state
return sun.misc.VM.toThreadState(threadStatus);
}
需要關注一個常常被忽略的方法
public static native boolean holdsLock(Object obj);
判斷當前執行緒是否持有鎖。
狀態變化的幾個方法
這幾個方法比較常見就不解釋了~
yield()
sleep(long millis)
sleep(long millis, int nanos)
start()
join(long)
join(long, int)
join()
run()
isAlive()
這幾個解釋一下:
interrupt(): 執行緒例項請求中斷
isInterrupted(): 返回執行緒例項是否中斷
interrupted(): 當前執行緒(currentThread方法)是否中斷
初始化
初始化主要了解兩個方法:
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
public Thread(ThreadGroup group, Runnable target, String name,long stackSize) {
init(group, target, name, stackSize);
}
其餘過載方法就是前三個引數的組合。
這裡我們不擴充講init方法,init方法將新執行緒和當前執行緒的絕大多數屬性都設定為一致。
這裡講一下未指定執行緒名時會設定為"Thread-" + nextThreadNum()
,而nextThreadNum是一個同步的方法:
/* For autonumbering anonymous threads. */
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
需要注意的是,這個是隻針對匿名初始化執行緒的!看下面的程式碼:
//原本的
System.out.println(new Thread().getName()); //Thread-0
System.out.println(new Thread().getName()); //Thread-1
System.out.println(new Thread().getName()); //Thread-2
//修改了中間的構造方法
System.out.println(new Thread().getName()); //Thread-0
System.out.println(new Thread("mid").getName()); //mid
System.out.println(new Thread().getName()); //Thread-1
一些其他獲取屬性的方法:
setPriority(int)
getPriority()
setName(String name)
getName()
getThreadGroup()
setDaemon(boolean isDaemon)
isDaemon()
getId()
getState()
Thread類中所有一些和ThreadGroup相關的方法:
activeCount() 獲取當前執行緒組中存活的執行緒數量
enumerate(Thread[] tarray) 獲取執行緒組的後輩執行緒數量
異常相關Debug相關
Thread中有一個和異常相關函式介面,當執行緒由於異常終止時不會觸發JVM的異常終止,而是會呼叫該介面的方法。
@FunctionalInterface
public interface UncaughtExceptionHandler {
/**
* Method invoked when the given thread terminates due to the
* given uncaught exception.
* <p>Any exception thrown by this method will be ignored by the
* Java Virtual Machine.
* @param t the thread
* @param e the exception
*/
void uncaughtException(Thread t, Throwable e);
}
例如:
原本會觸發JVM的異常機制:
public static void main(String[] args){
Thread thread1 = new Thread(()->{
throw new IllegalArgumentException("bug");
});
thread1.start();
}
// Exception in thread "Thread-0" java.lang.IllegalArgumentException: bug
修改後:
public static void main(String[] args){
Thread thread1 = new Thread(()->{
throw new IllegalArgumentException("bug");
});
thread1.setUncaughtExceptionHandler((Thread thread, Throwable throwable)->{
System.out.println("hhhh");
});
thread1.start();
}
//最終列印 hhhh
相應的有些方法:
setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh)
getDefaultUncaughtExceptionHandler
getUncaughtExceptionHandler
setUncaughtExceptionHandler(UncaughtExceptionHandler eh)
還有一些debug的方法也不介紹了:
getStackTrace
getAllStackTraces
checkAccess
dumpStack
上下文
setContextClassLoader(ClassLoader cl)方法和getContextClassLoader()通過下面這個例子理解~
public class SetContextLoader implements Runnable {
Thread thread;
public SetContextLoader() {
thread = new Thread(this);
thread.start();
}
public void run() {
ClassLoader classLoader = thread.getContextClassLoader();
/* Sets the context ClassLoader for this Thread. */
thread.setContextClassLoader(ClassLoader.getSystemClassLoader());
System.out.println("Class - " + classLoader.getClass());
System.out.println("Parent- " + classLoader.getParent());
}
public static void main(String args[]) {
new SetContextLoader();
}
}
輸出:
Class - class sun.misc.Launcher$AppClassLoader
Parent- sun.misc.Launcher$ExtClassLoader@757aef
相關文章
- Thread類及使用thread
- Java多執行緒(二):Thread類Java執行緒thread
- Java之Thread類的常用方法 .sleep()Javathread
- java多執行緒之Thread類Java執行緒thread
- Java多執行緒Thread類使用Java執行緒thread
- Thread類實現買電影案例thread
- 多執行緒系列(二)之Thread類執行緒thread
- thread 描述執行緒的一個類thread執行緒
- Java_Thread類的sleep()與SystemClock類的sleep()的區別Javathread
- Java Thread 類相關的幾個核心方法Javathread
- java併發程式設計:Thread類的使用Java程式設計thread
- muduo網路庫學習筆記(3):Thread類筆記thread
- java. 中 繼承Thread類建立執行緒.Java繼承thread執行緒
- python多執行緒之從Thread類繼承Python執行緒thread繼承
- Java併發程式設計:Thread類的使用介紹Java程式設計thread
- 02.併發程式設計(2)Thread類原始碼分析程式設計thread原始碼
- Threadthread
- 4-Thread類詳解與執行緒的狀態分析thread執行緒
- 多執行緒-繼承Thread類的方式賣電影票案例執行緒繼承thread
- Hello,Threadthread
- Thread jointhread
- 使用Thread類和Runnable介面實現多執行緒的區別thread執行緒
- Java之實現多執行緒的方式一 :繼承Thread類Java執行緒繼承thread
- Thread.jointhread
- Thread知識thread
- redolog threadthread
- Thread(C#)threadC#
- tomcat one connection one thread one request one threadTomcatthread
- .NET多執行緒程式設計(2):System.Threading.Thread類 (轉)執行緒程式設計thread
- muduo網路庫學習之Exception類、Thread 類封裝中的知識點(重點講pthread_atfork())Exceptionthread封裝
- thread local in pythonthreadPython
- Hystrix Thread Pool 解析thread
- Thread(執行緒)thread執行緒
- DUBBO Thread pool is EXHAUSTED!thread
- Thread原始碼剖析thread原始碼
- 深入Thread.sleepthread
- mysql 的thread poolMySqlthread
- (不要)使用std::threadthread