Java高併發編程學習筆記

1. 什麼是線程

在這裏插入圖片描述

2. 創建並啓動線程

2.1 正常情況

package com.liyang;

public class TryConcurrency {
    public static void main(String[] args) {
        readFromDadaBase();
        writeDataToFile();
    }

    /**
     * read data from database anf handle it...
     */
    private static void readFromDadaBase() {
        try {
            print("Begin read data from database...");
            Thread.sleep(1000 * 10L);
            print("Read data done and start handle it...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        print("The data handle finish and successfully...");
    }

    /**
     * write data to file...
     */
    private static void writeDataToFile() {
        try {
            print("Begin write data to file...");
            Thread.sleep(1000 * 20L);
            print("Read data done and start handle it...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        print("The data handle finish and successfully...");
    }

    /**
     * print the message from args
     * @param message
     */
    private static void print(String message) {
        System.out.println(message);
    }
}

2.2 創建一個線程 {extends Thread}

package com.ucs.thread;

public class Test {
    public static void main(String[] args) {
        new Thread("thread-1") {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    print("threda first ...");
                }
            }
        }.start();

        for (int i = 0; i < 10; i++) {
            print("main thread...");
        }
    }

    private static void print(String msg) {
        System.out.println("****"+msg+"****");
    }
}

2.3 創建一個線程 {implements Runnable}

我們查看文檔發現是這麼說的:
創建線程的另一種方法是聲明實現可運行接口的類。然後,該類實現run方法。然後可以分配類的實例,在創建線程時作爲參數傳遞,然後啓動。其他樣式中的相同示例如下所示:

     class PrimeRun implements Runnable {
         long minPrime;
         PrimeRun(long minPrime) {
             this.minPrime = minPrime;
         }

         public void run() {
             // compute primes larger than minPrime
              . . .
         }
     }
     PrimeRun p = new PrimeRun(143);
     new Thread(p).start();

2.4 線程生命週期

在這裏插入圖片描述

2.5 start方法解析

  1. 我們先去看看官方文檔

public void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
 
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
 
Throws:
IllegalThreadStateException - if the thread was already started.
See Also:
run(), stop()

使此線程開始執行;Java虛擬機調用此線程的run方法。
 
結果是兩個線程同時運行:當前線程(從對start方法的調用返回)和另一個線程(執行其run方法)。
 
多次啓動線程是不合法的。特別是,線程一旦完成執行,就不能重新啓動。會拋異常IllegalThreadStateException

  1. 去看看源碼
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".
	 */
	 /**
		*主方法線程或“系統”不調用此方法
		*由虛擬機創建/設置的組線程。添加的任何新功能
		*在將來,這個方法可能還必須添加到VM中。
		*零狀態值對應於狀態“NEW”。
	*/
	if (threadStatus != 0)
		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);

	boolean started = false;
	try {
		start0();
		started = true;
	} finally {
		try {
			if (!started) {
				group.threadStartFailed(this);
			}
		} catch (Throwable ignore) {
			/* do nothing. If start0 threw a Throwable then
			  it will be passed up the call stack */
			/*什麼都不做。如果拋異常
			它將在調用堆棧中被傳遞*/
		}
	}
}

// 這個是系統的方法 C++寫的
private native void start0();

未完待續…

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章