溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java并發知識點有哪些

發布時間:2022-03-28 16:13:49 來源:億速云 閱讀:162 作者:iii 欄目:編程語言

Java并發知識點有哪些

目錄

  1. 并發基礎

  2. Java并發工具類

  3. Java內存模型

  4. 線程池

  5. 并發設計模式

  6. 并發編程中的常見問題

  7. 并發編程的最佳實踐

  8. 并發編程的未來趨勢

1. 并發基礎

1.1 什么是并發

并發是指多個任務在同一時間段內交替執行,從宏觀上看,這些任務似乎是同時進行的。并發編程的目的是提高程序的執行效率,充分利用多核CPU的計算能力。

1.2 并發與并行的區別

并發和并行是兩個容易混淆的概念。并發是指多個任務在同一時間段內交替執行,而并行是指多個任務在同一時刻同時執行。并發可以通過時間片輪轉的方式實現,而并行則需要多核CPU的支持。

1.3 線程與進程

線程是操作系統調度的最小單位,一個進程可以包含多個線程。線程共享進程的內存空間,因此線程間的通信比進程間的通信更加高效。進程是操作系統資源分配的最小單位,每個進程都有獨立的內存空間。

1.4 線程的生命周期

線程的生命周期包括以下幾個狀態:

  • 新建(New):線程對象被創建,但尚未啟動。
  • 就緒(Runnable):線程已經啟動,等待CPU調度執行。
  • 運行(Running):線程正在執行。
  • 阻塞(Blocked):線程因為某些原因(如等待I/O操作)暫時停止執行。
  • 終止(Terminated):線程執行完畢或被強制終止。

1.5 線程的創建方式

在Java中,創建線程的方式主要有兩種:

  1. 繼承Thread:通過繼承Thread類并重寫run()方法來創建線程。
  2. 實現Runnable接口:通過實現Runnable接口并將其傳遞給Thread對象來創建線程。
// 方式1:繼承Thread類
class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Thread is running");
    }
}

// 方式2:實現Runnable接口
class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("Runnable is running");
    }
}

public class Main {
    public static void main(String[] args) {
        // 方式1
        MyThread thread1 = new MyThread();
        thread1.start();

        // 方式2
        Thread thread2 = new Thread(new MyRunnable());
        thread2.start();
    }
}

1.6 線程的優先級

線程的優先級決定了線程獲取CPU時間片的概率。Java中線程的優先級分為1(最低)到10(最高),默認優先級為5??梢酝ㄟ^setPriority()方法設置線程的優先級。

Thread thread = new Thread(() -> {
    System.out.println("Thread is running");
});
thread.setPriority(Thread.MAX_PRIORITY); // 設置最高優先級
thread.start();

1.7 線程的調度

線程調度是指操作系統決定哪個線程在何時執行的過程。Java中的線程調度是搶占式的,即高優先級的線程會優先執行,但具體的調度策略取決于操作系統的實現。

1.8 線程的同步與互斥

線程同步是指多個線程在訪問共享資源時,通過某種機制保證資源的一致性和正確性?;コ馐侵竿粫r刻只允許一個線程訪問共享資源。Java中常用的同步機制包括synchronized關鍵字和Lock接口。

1.9 線程的通信

線程通信是指多個線程之間通過某種機制進行信息交換。Java中常用的線程通信機制包括wait()、notify()notifyAll()方法。

class SharedResource {
    private boolean flag = false;

    public synchronized void produce() {
        while (flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Produced");
        flag = true;
        notify();
    }

    public synchronized void consume() {
        while (!flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Consumed");
        flag = false;
        notify();
    }
}

public class Main {
    public static void main(String[] args) {
        SharedResource resource = new SharedResource();

        Thread producer = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                resource.produce();
            }
        });

        Thread consumer = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                resource.consume();
            }
        });

        producer.start();
        consumer.start();
    }
}

1.10 線程的異常處理

線程中的異常如果沒有被捕獲,會導致線程終止??梢酝ㄟ^UncaughtExceptionHandler接口來捕獲線程中的未捕獲異常。

Thread thread = new Thread(() -> {
    throw new RuntimeException("Thread exception");
});

thread.setUncaughtExceptionHandler((t, e) -> {
    System.out.println("Exception in thread " + t.getName() + ": " + e.getMessage());
});

thread.start();

2. Java并發工具類

2.1 synchronized關鍵字

synchronized關鍵字用于實現線程同步,可以修飾方法或代碼塊。修飾方法時,鎖對象是當前實例;修飾靜態方法時,鎖對象是當前類的Class對象;修飾代碼塊時,鎖對象是括號內的對象。

class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("Count: " + counter.getCount());
    }
}

2.2 volatile關鍵字

volatile關鍵字用于保證變量的可見性,即一個線程對變量的修改對其他線程是可見的。volatile還可以防止指令重排序。

class SharedResource {
    private volatile boolean flag = false;

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public boolean getFlag() {
        return flag;
    }
}

public class Main {
    public static void main(String[] args) {
        SharedResource resource = new SharedResource();

        Thread t1 = new Thread(() -> {
            while (!resource.getFlag()) {
                // 等待flag變為true
            }
            System.out.println("Flag is true");
        });

        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            resource.setFlag(true);
            System.out.println("Flag set to true");
        });

        t1.start();
        t2.start();
    }
}

2.3 ReentrantLock

ReentrantLockLock接口的實現類,提供了比synchronized更靈活的鎖機制。ReentrantLock支持公平鎖和非公平鎖,并且可以中斷等待鎖的線程。

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Counter {
    private int count = 0;
    private Lock lock = new ReentrantLock();

    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }

    public int getCount() {
        return count;
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("Count: " + counter.getCount());
    }
}

2.4 ReadWriteLock

ReadWriteLock接口提供了讀寫鎖機制,允許多個讀線程同時訪問共享資源,但寫線程獨占訪問。ReentrantReadWriteLockReadWriteLock的實現類。

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class SharedResource {
    private int data = 0;
    private ReadWriteLock lock = new ReentrantReadWriteLock();

    public void write(int data) {
        lock.writeLock().lock();
        try {
            this.data = data;
            System.out.println("Write: " + data);
        } finally {
            lock.writeLock().unlock();
        }
    }

    public int read() {
        lock.readLock().lock();
        try {
            System.out.println("Read: " + data);
            return data;
        } finally {
            lock.readLock().unlock();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        SharedResource resource = new SharedResource();

        Thread writer = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                resource.write(i);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread reader = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                resource.read();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        writer.start();
        reader.start();
    }
}

2.5 Condition

Condition接口提供了類似于wait()notify()的線程通信機制,但更加靈活。Condition通常與ReentrantLock一起使用。

”`java import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;

class SharedResource { private boolean flag = false; private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition();

public void produce() {
    lock.lock();
    try {
        while (flag) {
            condition.await();
        }
        System.out.println("Produced");
        flag = true;
        condition.signal();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }
}

public void consume() {
    lock.lock();
    try {
        while (!flag) {
            condition.await();
        }
        System.out.println("Consumed");
        flag = false;
        condition.signal();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }
}

}

public class Main { public static void main(String[] args) { SharedResource resource = new SharedResource();

    Thread producer = new Thread(() -> {
        for (int i = 0; i < 5; i++) {
            resource.produce();
        }
    });

    Thread consumer = new Thread(() -> {
        for (int i = 0; i < 
向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女