Thread.currentThread() public static native Thread currentThread()to determine which thread is executing a segment of code Many of the methods in Thread are listed with some of the following modifiers: native, final, static, and synchronized. As a quick review, native methods are implemented in non-Java code (typically C or C++ in the JDK). Methods declared to be final may not be overridden in a subclass. When a method is static, it does not pertain to a particular instance of the class, but operates at the class level. The f3 synchronized modifier guarantees that no more than one thread is allowed to execute the statements inside a method at one time. Later in this book, the synchronized modifier is explained in detail. Thread類中有許多方法都有如下的修飾字:native:方法用非java代碼實現,如c、c++final:被申明為final的方法不能被子類覆蓋static:此方法不要類執行個體調用,用類名即可調用synchronized:保證只有同一時間只有一個線程能夠執行此方法 舉例/* * Created on 2005-7-6 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */package org.tju.msnrl.jonathan.thread.chapter1; /** * @author Administrator * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */public class CurrentThread extends Thread { private Thread createThread; public CurrentThread(){ this.createThread = Thread.currentThread(); } public void run(){ for(int i = 0; i < 10; i++) this.printMsg(); } public void printMsg(){ Thread t = Thread.currentThread(); if(t == this.createThread){ System.out.println("create thread"); } else if(t == this){ System.out.println("currect thread"); } else{ System.out.println("mystery thread"); } } public static void main(String[] args) { CurrentThread ct = new CurrentThread(); ct.start(); for(int i = 0; i < 10; i++) ct.printMsg(); }} 輸出結果:create threadcreate threadcreate threadcreate threadcreate threadcreate threadcreate threadcreate threadcreate threadcreate threadcurrect threadcurrect threadcurrect threadcurrect threadcurrect threadcurrect threadcurrect threadcurrect threadcurrect threadcurrect thread
getName() / setName() /*
* Created on 2005-7-6
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/package org.tju.msnrl.jonathan.thread.chapter1;
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates */public class GetSetThreadName extends Thread{ public void run(){
for(int i = 0; i < 10; i++)
this.printMsg();
} public void printMsg(){
Thread t = Thread.currentThread();
String threadName = t.getName();
System.out.println("name = " + threadName);
}
public static void main(String[] args) {
GetSetThreadName gstn = new GetSetThreadName();
gstn.setName("GetSetThreadName");
gstn.start();
for(int i = 0; i < 10; i++)
gstn.printMsg();
}
}
輸出結果:
name = main
name = main
name = main
name = main
name = main
name = main
name = main
name = main
name = main
name = main
name = GetSetThreadName
name = GetSetThreadName
name = GetSetThreadName
name = GetSetThreadName
name = GetSetThreadName
name = GetSetThreadName
name = GetSetThreadName
name = GetSetThreadName
name = GetSetThreadName
name = GetSetThreadNameThreads Started by the JavaVM
JDK 1.2:
main / Finalizer / Reference Handler / Signal dispatcher / AWT-Windows /AWT-EventQueue-0 / SunToolkit.PostEventQueue-0 / Screen UpdaterJava虛擬機器jdk1.2建立的線程名有:main、Finalizer、Reference Handler、Signal dispatcher、AWT-Windows、AWT-EventQueue-0、SunToolkit.PostEventQueue-0、Screen UpdaterNote that the Reference Handler, Signal dispatcher, and SunToolkit.PostEventQueue-0 threads are new to JDK 1.2. The threads named main and Finalizer (Reference Handler and Signal dispatcher for JDK 1.2) are started automatically for every application. The remaining threads are also started by the JavaVM when the application contains any graphical components from AWT or Swing. Therefore, in a JDK 1.2 application with a graphical user interface (GUI), eight threads are automatically started by the JavaVM.其中:main、Finalizer(jdk1.2以後還包括Reference Handler、Signal dispatcher)是每個應用都會自動建立的,如果應用程式涉及到圖形組件AWT/Swing,八個線程都會建立As mentioned previously, the main thread is responsible for starting application execution by invoking the main() method. This is the thread from which most other developer-defined threads are spawned by application code. The Finalizer thread is used by the JavaVM to execute the finalize() method of objects just before they are garbage collected. The AWT-EventQueue-0 thread is more commonly known as the event thread and invokes event-handling methods such as actionPerformed(), keyPressed(), mouseClicked(), and windowClosing().各個線程的作用如下:
main:應用程式主線程
Finalizer:是java虛擬機器執行finalize()方法進行垃圾收集
AWT-EventQueue-0:事件線程,調用訊息相應函數Although Java requires none of the following, it’s good practice to follow these conventions when naming threads:
1.Invoke setName() on the Thread before start(), and do not rename the Thread after it is started
2.Give each thread a brief, meaningful name when possible.
3.Give each thread a unique name.
4.Do not change the names of JavaVM threads, such as main.使用setName()函數的推薦用法:
1、線上程start()前調用
2、給線程起個儘可能簡潔明了的名字
3、線程名唯一
4、不要改變java虛擬機器建立的線程名,比如上面列出的八個
Thread Constructors核心建構函式如下:public Thread(ThreadGroup group, Runnable target, String name) ThreadGroup/Thread的關係就像檔案夾和檔案的關係,檔案夾中可以有檔案夾和檔案,ThreadGroup中可以同時包括ThreadGroup和Thread
target為實現了Runnable介面的類name為線程名
start() and isAlive()
public native synchronized void start()throws IllegalThreadStateException If the Thread has already been started, an IllegalThreadStateException will be thrown. When the start() method of a Thread is invoked, the new thread is considered to come alive. The thread remains alive until the run() method returns or until the thread is abruptly
stopped by the stop() method (which is a deprecated method, as of JDK 1.2!). start()函數必須捕獲IllegalThreadStateException異常,因為如果一個線程已經存在,此時再次調用start()則會拋出此異常 public final native boolean isAlive() can be used on Thread to test whether a thread has been started and is still running isAlive()判斷線程是否開始或正在運行中 /* * Created on 2005-7-6 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */package org.tju.msnrl.jonathan.thread.chapter1; /** * @author Administrator * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */public class IsAlive extends Thread { public void run(){ for(int i = 0; i < 10; i++) this.printMsg(); } public void printMsg(){ Thread t = Thread.currentThread(); String tName = t.getName(); System.out.println("name=" + tName); } public static void main(String[] args) { IsAlive ia = new IsAlive(); ia.setName("IsNameTester"); System.out.println("before start isAlive:" + ia.isAlive()); ia.start(); System.out.println("in runing isAlive:" + ia.isAlive()); for(int i = 0; i < 10; i++) ia.printMsg(); System.out.println("at end of main isAlive:" + ia.isAlive()); } }輸出結果:before start isAlive:falsein runing isAlive:truename=mainname=mainname=mainname=mainname=mainname=mainname=mainname=mainname=mainname=mainat end of main isAlive:truename=IsNameTestername=IsNameTestername=IsNameTestername=IsNameTestername=IsNameTestername=IsNameTestername=IsNameTestername=IsNameTestername=IsNameTestername=IsNameTester
Thread.sleep()
Sleeping is a much better option than using a busy loop. A sleeping thread does not use any processor cycles because its execution is suspended for the specified duration. 使用sleep而不是true迴圈,sleep是將線程掛起一定時間 The try/catch construct is necessary because while a thread is sleeping, it might be
interrupted by another thread. One thread might want to interrupt another to let it know that it should take some sort of action. Later chapters further explore the use of interrupts. Here, it suffices to say that a sleeping thread
might be interrupted and will throw an InterruptedException if this occurs. 使用sleep時必須捕獲InterruptedException異常,因為當進程sleep時,可能被別的進程打斷,此時會拋出此異常
/* * Created on 2005-7-6 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */package org.tju.msnrl.jonathan.thread.chapter1; /** * @author Administrator * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */public class Sleep extends Thread { public void run(){ this.loop(); } public void loop(){ Thread t = Thread.currentThread(); String name = t.getName(); System.out.println("just enter loop " + name); for(int i = 0; i < 10; i++){ try{ Thread.sleep(200); }catch(InterruptedException e){//必須捕獲此異常 } System.out.println("name =" + name); } System.out.println("be about to leave loop" + name); } public static void main(String[] args) { Sleep s = new Sleep(); s.setName("SleepTester"); s.start(); try{ Thread.sleep(700); }catch(InterruptedException e){ } s.loop(); }} 輸出結果:just enter loop SleepTestername =SleepTestername =SleepTestername =SleepTesterjust enter loop mainname =SleepTestername =mainname =SleepTestername =mainname =SleepTestername =mainname =SleepTestername =mainname =SleepTestername =mainname =SleepTestername =mainname =SleepTesterbe about to leave loopSleepTestername =mainname =mainname =mainname =mainbe about to leave loopmain