線程是程序內的一行執行。每個程序可以有多個關聯的線程。每個線程都有一個優先級,線程調度程序使用該優先級來確定哪個線程必須首先運行。 Java 提供了一個線程類,該類具有各種方法調用,以便通過提供構造函數和方法來對線程執行操作來管理線程的行為。
創建線程的方法
- 創建自己的類並擴展到父 Thread 類
- 實現 Runnable 接口。
下麵是偽代碼,您可以參考這些偽代碼來更好地了解今後 Thread 類的線程。
圖一:
// Way 1
// Creating thread By Extending To Thread class
class MyThread extends Thread {
// Method 1
// Run() method for our thread
public void run()
{
// Print statement
System.out.println(
"Thread is running created by extending to parent Thread class");
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Creating object of our thread class inside main()
// method
MyThread myThread = new MyThread();
// Starting the thread
myThread.start();
}
}
輸出
Thread is running created by extending to parent Thread class
插圖2:
// Way 2
// Creating thread using Runnable interface
class ThreadUsingInterface implements Runnable {
// Method 1
// run() method for the thread
public void run()
{
// Print statement
System.out.println("Thread is created using Runnable interface");
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Creating object of our thread class inside main()
// method
ThreadUsingInterface obj = new ThreadUsingInterface();
// Passing the object to thread in main()
Thread myThread = new Thread(obj);
// Starting the thread
myThread.start();
}
}
輸出
Thread is created using Runnable interface
Java中的線程類
線程是一個以 method() 開頭的程序,在此類中經常使用,僅稱為 start() 方法。此方法查找 run() 方法(該方法也是此類的方法),並開始執行 run() 方法的主體。這裏,請關注sleep()方法,稍後將討論該方法。
Note: Every class that is used as thread must implement Runnable interface and over ride it’s run method.
用法:
public class Thread extends Object implements Runnable
該類的構造函數如下:
構造函數 | 執行的操作 |
---|---|
Thread() | 分配一個新的 Thread 對象。 |
Thread(Runnable target) | 分配一個新的 Thread 對象。 |
Thread(Runnable target, String name) | 分配一個新的 Thread 對象。 |
Thread(String name) | 分配一個新的 Thread 對象。 |
Thread(ThreadGroup group, Runnable target) | 分配一個新的 Thread 對象。 |
Thread(ThreadGroup group, Runnable target, String name) | 分配一個新的 Thread 對象,使其以指定的名稱作為其運行對象,並屬於由組引用的線程組。 |
Thread(ThreadGroup group, Runnable target, String name, long stackSize) | 分配一個新的 Thread 對象,使其以指定的名稱作為其運行對象,屬於 group 引用的線程組,並具有指定的堆棧大小。 |
Thread(ThreadGroup group, String name) | 分配一個新的 Thread 對象。 |
Thread類的方法:
現在讓我們討論所有方法該類的說明如下:
方法 | 執行的操作 |
---|---|
activeCount() | 返回當前線程的線程組及其子組中活動線程數量的估計值 |
checkAccess() | 判斷當前運行的線程是否有權限修改該線程 |
clone() | 拋出CloneNotSupportedException,因為線程無法被有意義地克隆 |
currentThread() | 返回對當前正在執行的線程對象的引用 |
Java.lang.Thread | 將當前線程的堆棧跟蹤打印到標準錯誤流 |
枚舉(線程[] tarray) | 將當前線程的線程組及其子組中的每個活動線程複製到指定的數組中 |
getAllStackTraces() | 返回所有活動線程的堆棧跟蹤映射 |
Java.lang.Thread | 返回該線程的上下文ClassLoader |
Java.lang.Thread | 返回當線程由於未捕獲的異常而突然終止時調用的默認處理程序 |
getId() | 返回該線程的標識符 |
getName() | 返回該線程的名稱 |
getPriority() | 返回該線程的優先級 |
getStackTrace() | 返回表示該線程的堆棧轉儲的堆棧跟蹤元素數組 |
getState() | 返回該線程的狀態 |
Java.lang.Thread | 返回該線程所屬的線程組 |
Java.lang.Thread | 返回當該線程由於未捕獲的異常而突然終止時調用的處理程序 |
holdsLock(Object obj) | 當且僅當當前線程持有指定對象的監視器鎖時返回 true |
interrupt() | 中斷該線程 |
interrupted() | 測試當前線程是否被中斷 |
isAlive() | 測試該線程是否存活 |
isDaemon() | 測試該線程是否為守護線程 |
isInterrupted() | 測試該線程是否被中斷 |
join() | 等待該線程死亡 |
join(long millis) | 最多等待 millis 毫秒該線程終止 |
Thread.start()和Thread.run()的區別 | 如果該線程是使用單獨的 Runnable 運行對象構造的,則調用該 Runnable 對象的 run 方法;否則,此方法不執行任何操作並返回 |
Java.lang.Thread | 設置該線程的上下文ClassLoader |
setDaemon(boolean on) | 將此線程標記為守護線程或用戶線程 |
setDefaultUncaughtExceptionHandler( Thread.UncaughtExceptionHandler 呃) | 設置當線程由於未捕獲的異常而突然終止並且沒有為該線程定義其他處理程序時調用的默認處理程序 |
setName(String name) | 將此線程的名稱更改為等於參數名稱。 |
setUncaughtExceptionHandler( Thread.UncaughtExceptionHandler 呃) | 設置當該線程由於未捕獲的異常而突然終止時調用的處理程序 |
Java.lang.Thread | 更改該線程的優先級 |
sleep(long millis) | 使當前正在執行的線程休眠(暫時停止執行)指定的毫秒數,具體取決於係統計時器和調度程序的精度和準確性 |
start() | 導致該線程開始執行; Java虛擬機調用該線程的run方法 |
Java.lang.Thread | 返回該線程的字符串表示形式,包括線程的名稱、優先級和線程組 |
yield() | 向調度程序提示當前線程願意讓出其當前對處理器的使用 |
還要記住有一些從類java繼承的方法。 lang.Object 如下:
- equals()方法
- finalize()方法
- getClass()方法
- hashCode()方法
- notify()方法
- notify()和notifyAll()的區別
- Java.lang.Thread
- wait()方法
例子:Java程序演示Thread類的用法
// Java program Demonstrating Methods of Thread class
// Importing package
package generic;
// Class 1
// Helper class implementing Runnable interface
class Helper implements Runnable {
//
public void run() {
// Try block to check for exceptions
try {
// Print statement
System.out.println("thread2 going to sleep for 5000");
// Making thread sleep for 0.5 seconds
Thread.sleep(5000);
}
// Catch block to handle exception
catch (InterruptedException e) {
// Print statement
System.out.println("Thread2 interrupted");
}
}
}
// Class 2
// Helper class extending Runnable interface
public class Test implements Runnable {
// Method 1
// run() method of this class
public void run() {
// Thread run() method
}
// Method 2
// Main driver method
public static void main(String[] args) {
// Making objects of class 1 and 2 in main() method
Test obj = new Test();
Helper obj2 = new Helper();
// Creating 2 threads in main() method
Thread thread1 = new Thread(obj);
Thread thread2 = new Thread(obj2);
// Moving thread to runnable states
thread1.start();
thread2.start();
// Loading thread 1 in class 1
ClassLoader loader = thread1.getContextClassLoader();
// Creating 3rd thread in main() method
Thread thread3 = new Thread(new Helper());
// Getting number of active threads
System.out.println(Thread.activeCount());
thread1.checkAccess();
// Fetching an instance of this thread
Thread t = Thread.currentThread();
// Print and display commands
System.out.println(t.getName());
System.out.println("Thread1 name: " + thread1.getName());
System.out.println("Thread1 ID: " + thread1.getId());
// Fetching the priority and state of thread1
System.out.println("Priority of thread1 = " + thread1.getPriority());
// Getting the state of thread 1 using getState() method
// and printing the same
System.out.println(thread1.getState());
thread2 = new Thread(obj2);
thread2.start();
thread2.interrupt();
System.out.println("Is thread2 interrupted? " + thread2.interrupted() );
System.out.println("Is thread2 alive? " + thread2.isAlive());
thread1 = new Thread(obj);
thread1.setDaemon(true);
System.out.println("Is thread1 a daemon thread? " + thread1.isDaemon());
System.out.println("Is thread1 interrupted? " + thread1.isInterrupted());
// Waiting for thread2 to complete its execution
System.out.println("thread1 waiting for thread2 to join");
try {
thread2.join();
}
catch (InterruptedException e) {
// Display the exception along with line number
// using printStackTrace() method
e.printStackTrace();
}
// Now setting the name of thread1
thread1.setName("child thread xyz");
// Print and display command
System.out.println("New name set for thread 1" + thread1.getName());
// Setting the priority of thread1
thread1.setPriority(5);
thread2.yield();
// Fetching the string representation of thread1
System.out.println(thread1.toString());
// Getting list of active thread in current thread's group
Thread[] tarray = new Thread[3];
Thread.enumerate(tarray);
// Display commands
System.out.println("List of active threads:");
System.out.printf("[");
// Looking out using for each loop
for (Thread thread : tarray) {
System.out.println(thread);
}
// Display commands
System.out.printf("]\n");
System.out.println(Thread.getAllStackTraces());
ClassLoader classLoader = thread1.getContextClassLoader();
System.out.println(classLoader.toString());
System.out.println(thread1.getDefaultUncaughtExceptionHandler());
thread2.setUncaughtExceptionHandler(thread1.getDefaultUncaughtExceptionHandler());
thread1.setContextClassLoader(thread2.getContextClassLoader());
thread1.setDefaultUncaughtExceptionHandler(thread2.getUncaughtExceptionHandler());
thread1 = new Thread(obj);
StackTraceElement[] trace = thread1.getStackTrace();
System.out.println("Printing stack trace elements for thread1:");
for (StackTraceElement e : trace) {
System.out.println(e);
}
ThreadGroup grp = thread1.getThreadGroup();
System.out.println("ThreadGroup to which thread1 belongs " + grp.toString());
System.out.println(thread1.getUncaughtExceptionHandler());
System.out.println("Does thread1 holds Lock? " + thread1.holdsLock(obj2));
Thread.dumpStack();
}
}
輸出:
3
main
Thread1 name: Thread-0
Thread1 ID: 10
Priority of thread1 = 5
RUNNABLE
Is thread2 interrupted? false
Is thread2 alive? true
Is thread1 a daemon thread? true
Is thread1 interrupted? false
thread1 waiting for thread2 to join
thread2 going to sleep for 5000 ms
thread2 going to sleep for 5000 ms
Thread2 interrupted
New name set for thread 1child thread xyz
Thread[child thread xyz, 5, main]
List of active threads:
[Thread[main, 5, main]
Thread[Thread-1, 5, main]
null
]
{Thread[Signal Dispatcher, 9, system]=[Ljava.lang.StackTraceElement;@33909752,
Thread[Thread-1, 5, main]=[Ljava.lang.StackTraceElement;@55f96302,
Thread[main, 5, main]=[Ljava.lang.StackTraceElement;@3d4eac69,
Thread[Attach Listener, 5, system]=[Ljava.lang.StackTraceElement;@42a57993,
Thread[Finalizer, 8, system]=[Ljava.lang.StackTraceElement;@75b84c92,
Thread[Reference Handler, 10, system]=[Ljava.lang.StackTraceElement;@6bc7c054}
sun.misc.Launcher$AppClassLoader@73d16e93
null
Printing stack trace elements for thread1:
ThreadGroup to which thread1 belongs java.lang.ThreadGroup[name=main, maxpri=10]
java.lang.ThreadGroup[name=main, maxpri=10]
Does thread1 holds Lock? false
java.lang.Exception: Stack trace
at java.lang.Thread.dumpStack(Unknown Source)
at generic.Test.main(Test.java:111)
相關用法
- Java Java.lang.Thread.activeCount()用法及代碼示例
- Java Java.lang.Thread.checkAccess()用法及代碼示例
- Java Java.lang.Thread.currentThread()用法及代碼示例
- Java Java.lang.Thread.dumpStack()用法及代碼示例
- Java Java.lang.Thread.enumerate()用法及代碼示例
- Java Java.lang.Thread.getAllStackTraces()用法及代碼示例
- Java Java.lang.Thread.getContextClassLoader()用法及代碼示例
- Java Java.lang.Thread.getId()用法及代碼示例
- Java Java.lang.Thread.getName()用法及代碼示例
- Java Java.lang.Thread.getPriority()用法及代碼示例
- Java Java.lang.Thread.getStackTrace()用法及代碼示例
- Java Java.lang.Thread.getState()用法及代碼示例
- Java Java.lang.Thread.getThreadGroup()用法及代碼示例
- Java Java.lang.Thread.holdsLock()用法及代碼示例
- Java Java.lang.Thread.interrupt()用法及代碼示例
- Java Java.lang.Thread.interrupted()用法及代碼示例
- Java Java.lang.Thread.isAlive()用法及代碼示例
- Java Java.lang.Thread.isDaemon()用法及代碼示例
- Java Java.lang.Thread.isInterrupted()用法及代碼示例
- Java Java.lang.Thread.join()用法及代碼示例
- Java Java.lang.Thread.run()用法及代碼示例
- Java Java.lang.Thread.setContextClassLoader()用法及代碼示例
- Java Java.lang.Thread.setDaemon()用法及代碼示例
- Java Java.lang.Thread.setName()用法及代碼示例
- Java Java.lang.Thread.setPriority()用法及代碼示例
注:本文由純淨天空篩選整理自佚名大神的英文原創作品 Java.lang.Thread Class in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。