- 線程的概念:
幾乎每種操作系統(tǒng)都支持進程的概念 ----進程就是在某種程度上互相隔離的、獨立運行的程序。
進程---程序之間輪詢利用CPU時間。 進程是CPU任務。
線程---程序內部,輪詢利用程序得到的執(zhí)行時間。線程是某個程序的任務。
多進程(Multi-Thread)擴展了多進程(Multi-PRocess)操作的概念,將任務的劃分下降到了程序級別,使得各個程序似乎可以在同一時間內執(zhí)行多個任務。
每個任務稱為一個線程,能夠同時運行多個線程的程序稱為多線程程序。
多進程和多線程作為資源調度的兩種方式,已經存在了很久了。但是將線程顯示地作為程序語言的特征,而不是單純當底層操作系統(tǒng)的調度,Java是第一個主流的編程語言
其實,每個Java應用程序都至少有一個線程---主線程。當一個Java應用程序啟東時,JVM會創(chuàng)建主線程,并在該線程中調用程序的main()方法。
多進程和多線程有什么區(qū)別?對于進程來說,每個進程都有自己的一組完整的變量,而線程則共享相同的數據。
我們知道:計算機程序得以執(zhí)行的三個要素是:CPU、程序代碼和可存取的數據。在Java語言中,多線程的機制是通過虛擬CPU來實現的。
可以形象的理解為,在一個Java程序內部虛擬了多臺計算機,每臺計算機對應一個線程,有自己的CPU,可以獲取所需的代碼和數據,因此能獨立執(zhí)行任務,
相互間還可以公用代碼和數據。Java的線程是通過java.lang.Thread類來實現的,它內部實現了虛擬CPU的功能,能夠接收和處理傳遞給它的代碼和數據,并提供了
獨立的運行控制功能。
JVM還通常會創(chuàng)建一些其他的線程,不過,這些線程對我們而言通常是不可見的。例如,用于自動垃圾收集的線程、對象終止或者其他的JVM處理任務相關的線程。
方式一(繼承Thread類):
將一個類繼承Thread,然后覆蓋Thread中的run()方法,這樣就讓這個類本身也就成了線程類:
public class Aclass extends Thread{ … public void run(){ …. } …} Aclass a=new Aclass();a.start();//使用start()方法,線程進入Runnable(可運行狀態(tài)),它將向線程調度器注冊這個線程。不會馬上進入運行狀態(tài)(Running)
方式二(實現Runnable接口):
public Bclass implements Runnable{ public void run(){ … }}Bclass b =new Bclass();b.start();
補充知識:
public class Thread{…..….. public Thread(Runnable target) { init(null, target, "Thread-" + nextThreadNum(), 0); } private Runnable target; public void run() { if (target != null) { target.run(); } }/** * Causes this thread to begin execution; the Java Virtual Machine * calls the <code>run</code> method of this thread. * 讓這個線程執(zhí)行;JVM調用這個線程的run方法。 * <p> * The result is that two threads are running concurrently: the * current thread (which returns from the call to the * <code>start</code> method) and the other thread (which executes its * <code>run</code> method). * 結果是運行了兩個線程:當前線程(通過調用start方法)和另一個線程(執(zhí)行了它的run方法) * <p> * It is never legal to start a thread more than once. * 一個線程的start方法從來不會被調用兩次。 * In particular, a thread may not be restarted once it has completed * execution. *通常,一個線程可能別調用一次并執(zhí)行完成后,不必再次被執(zhí)行。 * @exception IllegalThreadStateException if the thread was already * started. * @see #run() * @see #stop() */ 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". */ if (threadStatus != 0 || this != me) throw new IllegalThreadStateException(); group.add(this); start0(); if (stopBeforeStart) { stop0(throwableFromStop); } } private native void start0();…..…..}
新聞熱點
疑難解答