天天看點

多線程之初識線程

建立線程

要了解多線程,肯定要先知道如何建立線程,建立線程的方式有三種,繼承 Thread 類、實作 Runnable 接口、實作 Callable 接口。

//建立線程方式一:繼承Thread類,重寫run()方法,調用start開啟線程

public class TestThread1 extends Thread {

@Override

public void run() {

//run方法線程體

for (int i = 0; i < 20; i++) {

System.out.println("我在學習 "+i);

}

}

public static void main(String[] args) {
    //main線程,主線程

    //建立一個線程對象
    TestThread1 testThread1 = new TestThread1();
    //調用start()方法開啟方法
    testThread1.start();

    for (int i = 0; i < 20; i++) {
        System.out.println("我在學習多線程 "+i);
    }
}
           

}

//建立線程方式2:實作runnable接口,重寫run方法,執行線程需要丢入runnable接口實作類,調用start方法

public class TestThread3 implements Runnable{

public void run() {

for (int i = 0; i < 20; i++) {

System.out.println(“我在看代碼”);

}

}

public static void main(String[] args) {

    //建立runnable接口的實作類對象
    TestThread3 testThread3 = new TestThread3();
    //建立線程對象,通過線程對象來開啟我們的線程,代理
    Thread thread = new Thread(testThread3);

    thread.start();

    for (int i = 0; i < 20; i++) {
        System.out.println("我在學習多線程");
    }
}
           

}

第三種通過一個下載下傳的 jar 包來示範,先導入依賴

commons-io commons-io 2.7 //線程建立方式三;實作Callable接口 //先導入一個依賴 public class TestCallable implements Callable {

private String url;
private String name;

public TestCallable(String url, String name) {
    this.url = url;
    this.name = name;
}

public Boolean call() throws Exception {
    webDownloader webDownloader = new webDownloader();
    webDownloader.downloader(url,name);
    System.out.println("下載下傳了檔案為"+name);
    return true;
}

public static void main(String[] args) throws ExecutionException, InterruptedException {
    TestCallable t1 = new TestCallable("圖檔位址", "1.jpg");
    TestCallable t2 = new TestCallable("圖檔位址", "2.jpg");
    TestCallable t3 = new TestCallable("圖檔位址", "3.jpg");

    //建立執行服務:
    ExecutorService ser = Executors.newFixedThreadPool(3);
    //送出執行服務
    Future<Boolean> r1 = ser.submit(t1);
    Future<Boolean> r2 = ser.submit(t2);
    Future<Boolean> r3 = ser.submit(t3);

    //擷取結果
    Boolean rs1 = r1.get();
    Boolean rs2 = r2.get();
    Boolean rs3 = r3.get();

    //關閉服務
    ser.shutdownNow();
}
           

}

//下載下傳器

class webDownloader{

public void downloader(String url,String name) {
    try {
        FileUtils.copyURLToFile(new URL(url),new File(name));
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("I0異常, downloader方法出現問題");
    }
}
           

}

線程不安全

死鎖條件

互斥條件:一個資源每次隻能被一個程序使用。

請求與保持條件:一個程序因請求資源而阻塞時,對已獲得的資源保持不放。

不剝奪條件:程序已獲得的資源,在末使用完之前,不能強行剝奪。

循環等待條件:若幹程序之間形成一種頭尾相接的循環等待資源關系。