最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java多線程從基礎到高級應用示例小結(jié)

 更新時間:2026年01月21日 15:33:03   作者:星河耀銀海  
本章介紹了Java多線程編程的基礎知識,包括線程的創(chuàng)建與管理、線程同步、線程通信和線程池,重點內(nèi)容包括線程的三種創(chuàng)建方式,通過本章的學習,讀者掌握了Java多線程編程的基本技能,感興趣的朋友跟隨小編一起看看吧

Java多線程:從基礎到高級應用

11.1 多線程概述

11.1.1 學習目標與重點提示

學習目標:理解多線程的基本概念,掌握線程的創(chuàng)建與管理方法,了解線程同步與通信的實現(xiàn)方式,掌握線程池的使用方法。
重點:線程的創(chuàng)建方式(繼承Thread類、實現(xiàn)Runnable接口、使用Callable和Future)、線程同步(synchronized、Lock)、線程通信(wait/notify、await/signal)、線程池(Executor、ThreadPoolExecutor)

11.1.2 多線程的基本概念

進程:一個正在運行的程序,包含代碼、數(shù)據(jù)和資源。
線程:進程內(nèi)部的一個執(zhí)行單元,共享進程的資源。
多線程:一個進程包含多個線程,同時執(zhí)行多個任務。

多線程的優(yōu)勢:

  • 提高程序的執(zhí)行效率。
  • 充分利用CPU資源。
  • 提高程序的響應速度。

多線程的劣勢:

  • 增加了程序的復雜度。
  • 容易出現(xiàn)線程安全問題。

11.2 線程的創(chuàng)建與管理

Java中創(chuàng)建線程的方式有三種:繼承Thread類、實現(xiàn)Runnable接口、使用Callable和Future。

11.2.1 繼承Thread類

定義:繼承Thread類,重寫run()方法,創(chuàng)建Thread子類的對象,調(diào)用start()方法啟動線程。
示例

class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
        }
    }
}
public class TestThread {
    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        thread1.start();
        thread2.start();
    }
}

輸出結(jié)果

Thread-0: 0
Thread-0: 1
Thread-1: 0
Thread-1: 1
Thread-0: 2
Thread-0: 3
Thread-1: 2
Thread-0: 4
Thread-1: 3
Thread-0: 5
Thread-0: 6
Thread-1: 4
Thread-0: 7
Thread-1: 5
Thread-0: 8
Thread-0: 9
Thread-1: 6
Thread-1: 7
Thread-1: 8
Thread-1: 9

? 結(jié)論:繼承Thread類的方式簡單,但Java不支持多繼承,因此這種方式有局限性。

11.2.2 實現(xiàn)Runnable接口

定義:實現(xiàn)Runnable接口,重寫run()方法,創(chuàng)建Runnable接口的實現(xiàn)類的對象,將該對象作為參數(shù)傳遞給Thread類的構(gòu)造方法,調(diào)用start()方法啟動線程。
示例

class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
        }
    }
}
public class TestRunnable {
    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
    }
}

輸出結(jié)果

Thread-0: 0
Thread-0: 1
Thread-1: 0
Thread-1: 1
Thread-0: 2
Thread-0: 3
Thread-1: 2
Thread-0: 4
Thread-1: 3
Thread-0: 5
Thread-0: 6
Thread-1: 4
Thread-0: 7
Thread-1: 5
Thread-0: 8
Thread-0: 9
Thread-1: 6
Thread-1: 7
Thread-1: 8
Thread-1: 9

? 結(jié)論:實現(xiàn)Runnable接口的方式避免了Java不支持多繼承的限制,但無法返回線程執(zhí)行結(jié)果。

11.2.3 使用Callable和Future

定義:實現(xiàn)Callable接口,重寫call()方法,創(chuàng)建Callable接口的實現(xiàn)類的對象,將該對象作為參數(shù)傳遞給FutureTask類的構(gòu)造方法,將FutureTask類的對象作為參數(shù)傳遞給Thread類的構(gòu)造方法,調(diào)用start()方法啟動線程,通過FutureTask類的get()方法獲取線程執(zhí)行結(jié)果。
示例

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i <= 100; i++) {
            sum += i;
        }
        return sum;
    }
}
public class TestCallable {
    public static void main(String[] args) {
        MyCallable callable = new MyCallable();
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        Thread thread = new Thread(futureTask);
        thread.start();
        try {
            int result = futureTask.get();
            System.out.println("1到100的和:" + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

輸出結(jié)果

1到100的和:5050

? 結(jié)論:使用Callable和Future的方式可以返回線程執(zhí)行結(jié)果,但需要使用FutureTask類。

11.3 線程同步

線程同步是指多個線程同時訪問共享資源時,保證資源的一致性和正確性。

11.3.1 synchronized關鍵字

定義:synchronized關鍵字用于實現(xiàn)線程同步,分為同步方法和同步塊。
示例

class Count {
    private int count = 0;
    public synchronized void increment() {
        count++;
        System.out.println(Thread.currentThread().getName() + ": " + count);
    }
}
class MyThread extends Thread {
    private Count count;
    public MyThread(Count count) {
        this.count = count;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            count.increment();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class TestSynchronized {
    public static void main(String[] args) {
        Count count = new Count();
        MyThread thread1 = new MyThread(count);
        MyThread thread2 = new MyThread(count);
        thread1.start();
        thread2.start();
    }
}

輸出結(jié)果

Thread-0: 1
Thread-1: 2
Thread-0: 3
Thread-1: 4
Thread-0: 5
Thread-1: 6
Thread-0: 7
Thread-1: 8
Thread-0: 9
Thread-1: 10
Thread-0: 11
Thread-1: 12
Thread-0: 13
Thread-1: 14
Thread-0: 15
Thread-1: 16
Thread-0: 17
Thread-1: 18
Thread-0: 19
Thread-1: 20

? 結(jié)論:synchronized關鍵字可以保證線程同步,但性能較低。

11.3.2 Lock接口

定義:Lock接口用于實現(xiàn)線程同步,提供了更靈活的同步方式,如可重入鎖、讀寫鎖等。
示例

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Count {
    private int count = 0;
    private Lock lock = new ReentrantLock();
    public void increment() {
        lock.lock();
        try {
            count++;
            System.out.println(Thread.currentThread().getName() + ": " + count);
        } finally {
            lock.unlock();
        }
    }
}
class MyThread extends Thread {
    private Count count;
    public MyThread(Count count) {
        this.count = count;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            count.increment();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class TestLock {
    public static void main(String[] args) {
        Count count = new Count();
        MyThread thread1 = new MyThread(count);
        MyThread thread2 = new MyThread(count);
        thread1.start();
        thread2.start();
    }
}

輸出結(jié)果

Thread-0: 1
Thread-1: 2
Thread-0: 3
Thread-1: 4
Thread-0: 5
Thread-1: 6
Thread-0: 7
Thread-1: 8
Thread-0: 9
Thread-1: 10
Thread-0: 11
Thread-1: 12
Thread-0: 13
Thread-1: 14
Thread-0: 15
Thread-1: 16
Thread-0: 17
Thread-1: 18
Thread-0: 19
Thread-1: 20

? 結(jié)論:Lock接口可以提供更靈活的同步方式,但需要手動釋放鎖。

11.4 線程通信

線程通信是指多個線程之間的協(xié)作,如生產(chǎn)者-消費者模型。

11.4.1 wait/notify方法

定義:wait/notify方法用于實現(xiàn)線程通信,wait()方法使線程進入等待狀態(tài),notify()方法喚醒等待的線程。
示例

class Warehouse {
    private int count = 0;
    private final int MAX_COUNT = 10;
    public synchronized void produce() throws InterruptedException {
        while (count == MAX_COUNT) {
            wait();
        }
        count++;
        System.out.println(Thread.currentThread().getName() + ": 生產(chǎn)了一個產(chǎn)品,當前產(chǎn)品數(shù)量:" + count);
        notifyAll();
    }
    public synchronized void consume() throws InterruptedException {
        while (count == 0) {
            wait();
        }
        count--;
        System.out.println(Thread.currentThread().getName() + ": 消費了一個產(chǎn)品,當前產(chǎn)品數(shù)量:" + count);
        notifyAll();
    }
}
class Producer extends Thread {
    private Warehouse warehouse;
    public Producer(Warehouse warehouse) {
        this.warehouse = warehouse;
    }
    @Override
    public void run() {
        try {
            for (int i = 0; i < 20; i++) {
                warehouse.produce();
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class Consumer extends Thread {
    private Warehouse warehouse;
    public Consumer(Warehouse warehouse) {
        this.warehouse = warehouse;
    }
    @Override
    public void run() {
        try {
            for (int i = 0; i < 20; i++) {
                warehouse.consume();
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class TestWaitNotify {
    public static void main(String[] args) {
        Warehouse warehouse = new Warehouse();
        Producer producer1 = new Producer(warehouse);
        Producer producer2 = new Producer(warehouse);
        Consumer consumer1 = new Consumer(warehouse);
        Consumer consumer2 = new Consumer(warehouse);
        producer1.start();
        producer2.start();
        consumer1.start();
        consumer2.start();
    }
}

輸出結(jié)果

Thread-0: 生產(chǎn)了一個產(chǎn)品,當前產(chǎn)品數(shù)量:1
Thread-1: 生產(chǎn)了一個產(chǎn)品,當前產(chǎn)品數(shù)量:2
Thread-2: 消費了一個產(chǎn)品,當前產(chǎn)品數(shù)量:1
Thread-3: 消費了一個產(chǎn)品,當前產(chǎn)品數(shù)量:0
Thread-0: 生產(chǎn)了一個產(chǎn)品,當前產(chǎn)品數(shù)量:1
Thread-1: 生產(chǎn)了一個產(chǎn)品,當前產(chǎn)品數(shù)量:2
Thread-2: 消費了一個產(chǎn)品,當前產(chǎn)品數(shù)量:1
Thread-3: 消費了一個產(chǎn)品,當前產(chǎn)品數(shù)量:0
...

? 結(jié)論:wait/notify方法可以實現(xiàn)線程通信,但需要在同步塊中使用。

11.4.2 await/signal方法

定義:await/signal方法用于實現(xiàn)線程通信,await()方法使線程進入等待狀態(tài),signal()方法喚醒等待的線程。
示例

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Warehouse {
    private int count = 0;
    private final int MAX_COUNT = 10;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    public void produce() throws InterruptedException {
        lock.lock();
        try {
            while (count == MAX_COUNT) {
                condition.await();
            }
            count++;
            System.out.println(Thread.currentThread().getName() + ": 生產(chǎn)了一個產(chǎn)品,當前產(chǎn)品數(shù)量:" + count);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
    public void consume() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0) {
                condition.await();
            }
            count--;
            System.out.println(Thread.currentThread().getName() + ": 消費了一個產(chǎn)品,當前產(chǎn)品數(shù)量:" + count);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
class Producer extends Thread {
    private Warehouse warehouse;
    public Producer(Warehouse warehouse) {
        this.warehouse = warehouse;
    }
    @Override
    public void run() {
        try {
            for (int i = 0; i < 20; i++) {
                warehouse.produce();
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class Consumer extends Thread {
    private Warehouse warehouse;
    public Consumer(Warehouse warehouse) {
        this.warehouse = warehouse;
    }
    @Override
    public void run() {
        try {
            for (int i = 0; i < 20; i++) {
                warehouse.consume();
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class TestAwaitSignal {
    public static void main(String[] args) {
        Warehouse warehouse = new Warehouse();
        Producer producer1 = new Producer(warehouse);
        Producer producer2 = new Producer(warehouse);
        Consumer consumer1 = new Consumer(warehouse);
        Consumer consumer2 = new Consumer(warehouse);
        producer1.start();
        producer2.start();
        consumer1.start();
        consumer2.start();
    }
}

輸出結(jié)果

Thread-0: 生產(chǎn)了一個產(chǎn)品,當前產(chǎn)品數(shù)量:1
Thread-1: 生產(chǎn)了一個產(chǎn)品,當前產(chǎn)品數(shù)量:2
Thread-2: 消費了一個產(chǎn)品,當前產(chǎn)品數(shù)量:1
Thread-3: 消費了一個產(chǎn)品,當前產(chǎn)品數(shù)量:0
Thread-0: 生產(chǎn)了一個產(chǎn)品,當前產(chǎn)品數(shù)量:1
Thread-1: 生產(chǎn)了一個產(chǎn)品,當前產(chǎn)品數(shù)量:2
Thread-2: 消費了一個產(chǎn)品,當前產(chǎn)品數(shù)量:1
Thread-3: 消費了一個產(chǎn)品,當前產(chǎn)品數(shù)量:0
...

? 結(jié)論:await/signal方法可以提供更靈活的線程通信方式,但需要使用Lock接口。

11.5 線程池

線程池是一種管理線程的方式,用于減少線程的創(chuàng)建和銷毀開銷。

11.5.1 Executor框架

定義:Executor框架是Java提供的線程池管理框架,包括Executor、ExecutorService、ThreadPoolExecutor等類。
示例

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class MyRunnable implements Runnable {
    private int taskId;
    public MyRunnable(int taskId) {
        this.taskId = taskId;
    }
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + ": 執(zhí)行任務" + taskId);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + ": 任務" + taskId + "完成");
    }
}
public class TestExecutor {
    public static void main(String[] args) {
        // 創(chuàng)建線程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        // 提交任務
        for (int i = 0; i < 10; i++) {
            executorService.submit(new MyRunnable(i));
        }
        // 關閉線程池
        executorService.shutdown();
    }
}

輸出結(jié)果

pool-1-thread-1: 執(zhí)行任務0
pool-1-thread-2: 執(zhí)行任務1
pool-1-thread-3: 執(zhí)行任務2
pool-1-thread-1: 任務0完成
pool-1-thread-1: 執(zhí)行任務3
pool-1-thread-2: 任務1完成
pool-1-thread-2: 執(zhí)行任務4
pool-1-thread-3: 任務2完成
pool-1-thread-3: 執(zhí)行任務5
pool-1-thread-1: 任務3完成
pool-1-thread-1: 執(zhí)行任務6
pool-1-thread-2: 任務4完成
pool-1-thread-2: 執(zhí)行任務7
pool-1-thread-3: 任務5完成
pool-1-thread-3: 執(zhí)行任務8
pool-1-thread-1: 任務6完成
pool-1-thread-1: 執(zhí)行任務9
pool-1-thread-2: 任務7完成
pool-1-thread-3: 任務8完成
pool-1-thread-1: 任務9完成

? 結(jié)論:Executor框架可以方便地管理線程池,但需要根據(jù)實際需求選擇合適的線程池類型。

總結(jié)

本章我們學習了Java的多線程,包括線程的創(chuàng)建與管理、線程同步、線程通信、線程池等內(nèi)容。其中,線程的創(chuàng)建方式(繼承Thread類、實現(xiàn)Runnable接口、使用Callable和Future)、線程同步(synchronized、Lock)、線程通信(wait/notify、await/signal)、線程池(Executor、ThreadPoolExecutor)是本章的重點內(nèi)容。從下一章開始,我們將學習Java的網(wǎng)絡編程、數(shù)據(jù)庫編程等內(nèi)容。

到此這篇關于Java多線程從基礎到高級應用示例小結(jié)的文章就介紹到這了,更多相關java多線程應用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

土默特右旗| 临汾市| 榆树市| 安西县| 武陟县| 油尖旺区| 沁阳市| 阜阳市| 潜江市| 尉犁县| 大连市| 武城县| 长武县| 卢龙县| 东丰县| 麻栗坡县| 太湖县| 项城市| 天等县| 萨迦县| 禹州市| 石门县| 黔西县| 弥勒县| 冀州市| 巨鹿县| 青田县| 北安市| 三河市| 忻州市| 灵武市| 六枝特区| 湾仔区| 炉霍县| 济源市| 崇礼县| 江西省| 临邑县| 松阳县| 武城县| 丰原市|