在Java中,線程阻塞通常是由于線程在等待某個條件滿足或者等待某個資源可用而導致的。為了處理線程阻塞,我們可以采用以下幾種方法:
public class BlockingExample {
private static final Object lock = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 1 acquired lock");
try {
// 模擬等待條件滿足
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 released lock");
}
});
Thread thread2 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 2 acquired lock");
System.out.println("Thread 2 released lock");
}
});
thread1.start();
thread2.start();
}
}
public class BlockingExample {
private static final Object lock = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 1 acquired lock");
try {
// 模擬等待條件滿足
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 released lock");
}
});
Thread thread2 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 2 acquired lock");
// 模擬條件滿足
System.out.println("Notifying Thread 1");
lock.notify();
System.out.println("Thread 2 released lock");
}
});
thread1.start();
thread2.start();
}
}
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class BlockingExample {
public static void main(String[] args) {
BlockingQueue<String> queue = new LinkedBlockingQueue<>(1);
Thread thread1 = new Thread(() -> {
try {
String item = queue.take();
System.out.println("Thread 1 received: " + item);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread2 = new Thread(() -> {
try {
queue.put("Hello");
System.out.println("Thread 2 sent: Hello");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread1.start();
thread2.start();
}
}
這些方法都可以用于處理Java線程阻塞問題。在實際應用中,我們需要根據具體場景選擇合適的方法來實現線程間的通信和協作。