synchronized
關鍵字volatile
關鍵字ReentrantLock
ReadWriteLock
Condition
Semaphore
CountDownLatch
CyclicBarrier
Phaser
Exchanger
ForkJoinPool
CompletableFuture
ThreadLocal
Atomic
類BlockingQueue
ConcurrentHashMap
CopyOnWriteArrayList
StampedLock
LockSupport
Future
與FutureTask
并發是指多個任務在同一時間段內交替執行,從宏觀上看,這些任務似乎是同時進行的。并發編程的目的是提高程序的執行效率,充分利用多核CPU的計算能力。
并發和并行是兩個容易混淆的概念。并發是指多個任務在同一時間段內交替執行,而并行是指多個任務在同一時刻同時執行。并發可以通過時間片輪轉的方式實現,而并行則需要多核CPU的支持。
線程是操作系統調度的最小單位,一個進程可以包含多個線程。線程共享進程的內存空間,因此線程間的通信比進程間的通信更加高效。進程是操作系統資源分配的最小單位,每個進程都有獨立的內存空間。
線程的生命周期包括以下幾個狀態:
在Java中,創建線程的方式主要有兩種:
Thread
類:通過繼承Thread
類并重寫run()
方法來創建線程。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();
}
}
線程的優先級決定了線程獲取CPU時間片的概率。Java中線程的優先級分為1(最低)到10(最高),默認優先級為5??梢酝ㄟ^setPriority()
方法設置線程的優先級。
Thread thread = new Thread(() -> {
System.out.println("Thread is running");
});
thread.setPriority(Thread.MAX_PRIORITY); // 設置最高優先級
thread.start();
線程調度是指操作系統決定哪個線程在何時執行的過程。Java中的線程調度是搶占式的,即高優先級的線程會優先執行,但具體的調度策略取決于操作系統的實現。
線程同步是指多個線程在訪問共享資源時,通過某種機制保證資源的一致性和正確性?;コ馐侵竿粫r刻只允許一個線程訪問共享資源。Java中常用的同步機制包括synchronized
關鍵字和Lock
接口。
線程通信是指多個線程之間通過某種機制進行信息交換。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();
}
}
線程中的異常如果沒有被捕獲,會導致線程終止??梢酝ㄟ^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();
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());
}
}
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();
}
}
ReentrantLock
ReentrantLock
是Lock
接口的實現類,提供了比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());
}
}
ReadWriteLock
ReadWriteLock
接口提供了讀寫鎖機制,允許多個讀線程同時訪問共享資源,但寫線程獨占訪問。ReentrantReadWriteLock
是ReadWriteLock
的實現類。
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();
}
}
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 <
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。