Article by :Jeff Langr
Writing well-behaved, multi-threaded applications is one of the more challenging aspects of Java coding.One of the best ways to write multi-threaded applications is to take advantage of known threading patterns.Queues are common constructs in multithreaded applications. Clients add requests to a queue. A server retrieves requests from the queue. When no requests are available in the queue, the server waits for entries to be posted to it.
Prior to Java 5, you'd have to build such a queue yourself. It's not terribly difficult, but you'd need to worry about all of the synchronization points yourself. There are many ways to code a solution, and most of them are going to contain insidious concurrency defects.
Fortunately, you no longer need to build your own thread-safe queue. Java 5 provides a number of utility classes for multithreaded applications. You'll find these classes in the java.util.concurrent, java.utilconcurrent.atomic, and java.util.concurrent.locks packages. These classes are largely based on Doug Lea's work and book Concurrent Programming in Java. Lea's book is considered the bible for multithreaded Java programming.The very first interface listed in java.util.concurrent is BlockingQueue, a java.util.Queue subclass. When clients attempt to retrieve elements but none are available, a BlockingQueue encapsulates code that waits until an element becomes available. The Queue class, also new to Java 5, is a new collection class that supports the classic concept of a FIFO (first-in, first out) data structure. Other Java 5 queue implementations include support for removal based on priority, and a collection that acts like a stack.
Listing 1. Server
Listing 1. shows a simple server class based on use of a BlockingQueue. The server runs infinitely, accepting requests from a client. Clients can send requests asynchronously and rapidly—the server only adds a client request to the server's queue, then returns immediately to the client. A separate server thread loops indefinitely, asking the BlockingQueue to return when a new request becomes available. Once a request is available, it's removed from the queue. The server then handles the request.
The server(Server.java):
import java.util.concurrent.*;
public class Server extends Thread {
private BlockingQueue<Request> queue =
new LinkedBlockingQueue<Request>();//use a queue to store thread
public void accept(Request request) {
queue.add(request);
}
public void run() {
while (true) //server runs infinitely, accepting requests from a client.
try {
execute(queue.take());
}
catch (InterruptedException e) {
}
}
private void execute(final Request request) {
new Thread(new Runnable() {
public void run() {
request.execute();
}
}).start();
}
}
In this server implementation, I chose to execute requests coming off the queue by spawning them in an entirely new thread.
But, it might make more sense to constrain the overall number of threads concurrently executing. It's not terribly efficient to execute large numbers of threads simultaneously. I'll explore the concept of thread pools, which can address this concern, in a future article.
Let's work through the code. I first create a BlockingQueue field named queue, assigning to it a LinkedBlockingQueue instance.
In a LinkedBlockingQueue, elements get added to the tail of the queue. The element stored on the queue the longest is the head,and thus is the next element to be retrieved.
The accept method runs in the primary thread of Server, adding requests to the queue as they arrive. A request is simply a class that implements the Request interface (see Listing 2).
Listing 2. Request.
The Interface (Request.java):
public interface Request {
void execute();
}
The run method executes in a second server thread, looping infinitely. It invokes the take method on the queue, which will block until a request is available. Once a request is available, it's removed from the queue and returned from the call to take. At that point, I call the local Server method execute to process the request. As mentioned before, execute spawns and executes a new Thread object for each request.
Listing 3. Client.
Listing 3 shows sample client code that exercises the Server class.
The Test Client(Client.java)
import java.util.*;
public class Client {
public static void main(String[] args) {
new Client().go();
}
public void go() {
final Server server = new Server();
server.start();
for (int i = 0; i < 10; i++) {
final Request request = createRequest(i);
server.accept(request);
}
}
Request createRequest(final int index) {
return new Request() {
public void execute() {
for (int i = 0; i <= 100; i += 10) {
sleep((new Random().nextInt(5) + 1) * 1000);
System.out.println(
String.format(
"request: %d completed: %d%%", index, i));
}
System.out.println(
String.format("reqest %d completed", index));
}
};
}
private void sleep(int millis) {
try {
Thread.sleep(millis);
}
catch (InterruptedException e) {
}
}
}
You might want to constrain the queue itself to support only so many incoming requests. In listing 4,
I create a Server with a capacity of two. As long as a queue is empty, the add method returns the boolean value true. But, once the queue contains two elements, attempts to add additional elements immediately throw an IllegalStateException. Instead of using add, then, I chose to use the offer method, also defined in the BlockingQueue interface. This method returns false immediately when the queue is already full.
Listing 4. A limited capacity queue.
public class Server extends Thread {
static final int CAPACITY = 2;//
private BlockingQueue<Request> queue =
new LinkedBlockingQueue<Request>(CAPACITY);
public boolean accept(Request request) {
return queue.offer(request);
}
...
I've altered the accept method to return the result of the offer call. This makes the client aware of the problem. Client code can resubmit the request, or display a message to the user indicating that the server is busy. Another form of offer allows you to specify a timeout period, in which case the BlockingQueue will wait up to that period to retrieve an element when the queue is empty.
An alternative is to use the BlockingQueue method put (see Listing 5). Calls to this method will block until the queue has available capacity.
Listing 5. Blocking on add.
public class Server extends Thread {
static final int CAPACITY = 2;
private BlockingQueue<Request> queue =
new LinkedBlockingQueue<Request>(CAPACITY);
public void accept(Request request) {
try {
queue.put(request);
}
catch (InterruptedException e) {
throw new RuntimeException("add to queue interrupted");
}
}
...
In the past, I've spent painstaking hours building multithreaded support into my own applications.
Worse, I was rarely certain that my code was completely thread-safe. BlockingQueue is one very useful building block that can help you quickly and confidently build your own multithreaded applications.
Summary:
This article show us some mode how to implement Multi-threaded Application safety with BlockingQueue. Listing 4 and Listing 5 also inspire us how to create a Thead Pool for us Application.
分享到:
相关推荐
标题 "rknn-multi-threaded-nosigmoid.zip" 暗示了这个压缩包可能包含一个或多个关于RKNN(RISC-V Neural Network Kernel)的多线程实现,并且在模型中省略了Sigmoid激活函数。RKNN是针对RISC-V架构优化的神经网络...
综上所述,"get-system-time-in-Multi-threaded.rar_In Time"的示例可能涉及到多线程的创建、执行、定时以及线程安全的系统时间获取。在实际应用中,理解这些概念并熟练运用它们,对于编写高效的并发程序是至关重要...
标题中的“多线程精品资源--Chrome multi-threaded download manager extension”揭示了这是一个关于Chrome浏览器的多线程下载管理器扩展程序的资源集合。多线程下载管理器是一种能够利用多个连接同时下载文件的工具...
标题中的“TCP/IP多线程web服务器实现,Multi-Threaded Web Server java实现多网页请求访问”揭示了我们要讨论的核心技术点,即如何使用Java语言实现一个基于TCP/IP协议的多线程Web服务器。Web服务器的主要任务是...
"linux-ix86-threaded"部分表明该版本是为32位Linux系统设计的,并且支持多线程。这意味着可以在单个进程中同时执行多个Tcl脚本,提高程序的并发性和效率。这对于处理大量并发请求或执行并行计算的任务特别有用。 ...
MTTTY (Multi-Threaded TTY) 是一个容易使用的高效 Win 32 串行通信程序 文章“Serial Communications in Win32”提到的工具 类似超级终端中串口部分的程序,很不错 这个已经移植到vs2008上面的版本,debug 文件夹有...
这个压缩包是线程安全的,意味着它支持多线程编程,这对于在多核处理器上运行的系统来说尤其重要。TCL是一种动态编程语言,常用于脚本编写、自动化任务、GUI开发以及测试套件等。 描述中提到,这个包可能是为在ARM...
正在进行中的一本书,着重介绍如何使用Java语言进行面向对象的多线程设计和编程。
此外,为了保证搜索性能,可能会采用并发友好的数据结构,比如`ConcurrentHashMap`来存储搜索结果,以便在多个线程之间安全地共享数据。 总之,这个实例展示了如何利用多线程技术优化文件搜索,通过并行化处理提高...
Chrome multi-threaded download manager extension,based on Aria2 and AriaNg. Chrome多线程下载扩展。.zip,Chrome multi-threaded download manager extension,based on Aria2 and AriaNg. Chrome多线程下载扩展...
本资源"Multi_Threaded_Client_Server.rar_Server_多线程"是一个C++实现的多线程客户端-服务器(Client-Server)示例,非常适合初学者学习和理解这一技术。 首先,我们来了解多线程的基本概念。在单线程程序中,...
ActiveTcl8.6.4.1.299124-win32-ix86-threaded.exe
Multithreaded, libevent-based socket server. http://sourceforge.net/p/libevent-thread/code/ci/master/tree/README
ActiveTcl8.4.11.2.201775-win32-ix86-threaded.exe 包含了很多库,另外是支持win32,32bit的老版本
"Multi-threaded-transfer.rar"这个压缩包中的资源显然与使用Java进行多线程文件传输有关。下面我们将详细探讨多线程和Java文件传输的相关知识点。 首先,多线程(Multi-threading)是指在一个程序中同时运行多个...
标题 "Multi-threaded Client/Server Socket Class" 描述的是一个实现了多线程客户端/服务器套接字类的软件模块。这个系统设计允许同时处理多个客户端连接,提高服务器的并发处理能力,是网络编程中常见的模式。 在...
标题"ActiveTcl8.6.3.1.298624-win32-ix86-threaded"表明这是一个针对Windows 32位Intel x86架构的ActiveTcl版本,版本号为8.6.3.1,构建号为298624,且支持多线程。这意味着它可以充分利用多核处理器的性能,提高...
ActiveTcl8.4.16.0.282109-win32-ix86-threaded
"Multi-threaded-HTTP-procedures.rar" 提供了一个多线程HTTP断点续传程序的实例,旨在帮助开发者理解和实现这一功能,提高文件下载的效率和用户体验。 首先,我们来理解一下“多线程”和“HTTP断点续传”的概念。...