1. 线程阻塞
优点:
可以控制线程的执行顺序和并发度。
可以避免资源竞争和数据一致性问题。
缺点:
阻塞的线程会占用系统资源,降低系统的并发能力。
阻塞可能导致程序整体性能下降。
示例:生产者-消费者模型
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
class Producer implements Runnable {
private BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
queue.put(i);
System.out.println("Produced: " + i);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
private BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
try {
int number = queue.take();
System.out.println("Consumed: " + number);
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(5);
Thread producerThread = new Thread(new Producer(queue));
Thread consumerThread = new Thread(new Consumer(queue));
producerThread.start();
consumerThread.start();
}
}
2. IO阻塞
优点:
简单易用,适用于处理低并发的IO操作。
节省系统资源,避免上下文切换占用的系统资源。
缺点:
单线程下,一个IO操作的阻塞会导致整个程序无法响应其他请求。
需要有效地处理异常,防止IO阻塞导致的程序异常退出。
示例:简单的服务器
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class SimpleServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8080);
while (true) {
Socket clientSocket = serverSocket.accept();
handleClient(clientSocket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void handleClient(Socket clientSocket) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received: " + inputLine);
out.println("ServerResponse: " + inputLine);
if (inputLine.equals("bye")) {
break;
}
}
in.close();
out.close();
clientSocket.close();
}
}
3. 同步阻塞
优点:
简化多线程编程,避免资源竞争和数据一致性问题。
提供了对共享资源的安全访问方式。
缺点:
同步阻塞会降低程序的并发性能。
锁粒度不当或死锁可能导致程序出现性能问题或无法响应。
示例:银行账户转账
class BankAccount {
private double balance;
public BankAccount(double balance) {
this.balance = balance;
}
public synchronized void deposit(double amount) {
balance += amount;
}
public synchronized void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000);
Thread depositThread = new Thread(() -> {
for (int i = 0; i < 10; i++) {
account.deposit(100);
System.out.println("Deposited: 100");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread withdrawThread = new Thread(() -> {
for (int i = 0; i < 10; i++) {
account.withdraw(100);
System.out.println("Withdrawn: 100");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
depositThread.start();
withdrawThread.start();
}
}
4. 异步非阻塞
优点:
可以实现高并发、高吞吐量的处理能力。
非阻塞的特性可以提高系统的响应速度和资源利用率。
缺点:
编程模型相对复杂,需要处理回调函数或使用异步框架。
异步操作可能引发更多的程序错误,如并发访问问题。
示例:HTTP服务器
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
public class SimpleHttpServer {
public static void main(String[] args) throws Exception {
AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(8080));
serverSocketChannel.accept(null, new CompletionHandler<>() {
@Override
public void completed(AsynchronousSocketChannel clientSocketChannel, Object attachment) {
serverSocketChannel.accept(null, this);
handleClient(clientSocketChannel);
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
while (true) {
Thread.sleep(1000);
}
}
private static void handleClient(AsynchronousSocketChannel clientSocketChannel) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
clientSocketChannel.read(buffer, null, new CompletionHandler<>() {
@Override
public void completed(Integer bytesRead, Object attachment) {
if (bytesRead > 0) {
buffer.flip();
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
String request = new String(data).trim();
System.out.println("Received: " + request);
String response = "HTTP/1.1 200 OK\r\n" +
"Content-Length: 12\r\n" +
"\r\n" +
"Hello World!";
buffer.clear();
buffer.put(response.getBytes());
buffer.flip();
clientSocketChannel.write(buffer, null, this);
} else {
try {
clientSocketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
}
}
5.关系和转换:
5.1 线程阻塞是基础,可以在IO阻塞、同步阻塞以及异步非阻塞中运用。
5.2 IO阻塞适用于低并发场景,简单易用,但可能造成整个程序的阻塞。
5.3 同步阻塞通过加锁等方式来避免资源竞争,但会降低程序的并发性能。
5.4 异步非阻塞通过回调函数或事件驱动的方式实现高并发处理,但编程模型复杂。
互相之间的转换可以通过线程池、异步回调、异步框架等实现,具体根据需求选择合适的转换方式。