Java并发编程实例--16.使用ReentrantLock实现线程同步
Java提供另一机制去同步代码块。它比synchronized关键字更强大且易用。
它是基于Lock接口和其实现类例如:ReentrantLock。
这一机制对比synchronized关键字的优势在于:
1.可以构建更加灵活的同步代码块;
2.Lock接口提供了一些额外功能,例如tryLock()方法,它会返回一个布尔值以表示当前资源是否被锁。
3.Lock接口可以实现读写分离,多个读者但只有一个修改者。
4.Lock接口提供更好的性能。
本例中,我们将通过模拟打印队列去学习如何使用锁去同步代码块。
PrintQueue.java
package com.dylan.thread.ch2.c04.task;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* This class simulates a print queue
*
*/
public class PrintQueue {
/**
* Lock to control the access to the queue.
*/
private final Lock queueLock=new ReentrantLock();
/**
* Method that prints a document
* @param document document to print
*/
public void printJob(Object document){
queueLock.lock();
try {
Long duration=(long)(Math.random()*10000);
System.out.printf("%s: PrintQueue: Printing a Job during %d seconds\n",Thread.currentThread().getName(),(duration/1000));
Thread.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
queueLock.unlock();
}
}
}
Job.java
package com.dylan.thread.ch2.c04.task;
/**
* This class simulates a job that send a document to print.
*
*/
public class Job implements Runnable {
/**
* Queue to print the documents
*/
private PrintQueue printQueue;
/**
* Constructor of the class. Initializes the queue
* @param printQueue
*/
public Job(PrintQueue printQueue){
this.printQueue=printQueue;
}
/**
* Core method of the Job. Sends the document to the print queue and waits
* for its finalization
*/
@Override
public void run() {
System.out.printf("%s: Going to print a document\n",Thread.currentThread().getName());
printQueue.printJob(new Object());
System.out.printf("%s: The document has been printed\n",Thread.currentThread().getName());
}
}
Main.java
package com.dylan.thread.ch2.c04.core;
import com.dylan.thread.ch2.c04.task.Job;
import com.dylan.thread.ch2.c04.task.PrintQueue;
/**
* Main class of the example.
*
*/
public class Main {
/**
* Main method of the class. Run ten jobs in parallel that
* send documents to the print queue at the same time.
*/
public static void main (String args[]){
// Creates the print queue
PrintQueue printQueue=new PrintQueue();
// Creates ten Threads
Thread thread[]=new Thread[10];
for (int i=0; i<10; i++){
thread[i]=new Thread(new Job(printQueue),"Thread "+i);
}
// Starts the Threads
for (int i=0; i<10; i++){
thread[i].start();
}
}
}
运行结果:
Thread 0: Going to print a document
Thread 5: Going to print a document
Thread 0: PrintQueue: Printing a Job during 0 seconds
Thread 8: Going to print a document
Thread 7: Going to print a document
Thread 3: Going to print a document
Thread 1: Going to print a document
Thread 4: Going to print a document
Thread 2: Going to print a document
Thread 9: Going to print a document
Thread 6: Going to print a document
Thread 0: The document has been printed
Thread 5: PrintQueue: Printing a Job during 7 seconds
Thread 5: The document has been printed
Thread 8: PrintQueue: Printing a Job during 0 seconds
Thread 7: PrintQueue: Printing a Job during 5 seconds
Thread 8: The document has been printed
Thread 7: The document has been printed
Thread 3: PrintQueue: Printing a Job during 7 seconds
Thread 3: The document has been printed
Thread 1: PrintQueue: Printing a Job during 3 seconds
Thread 1: The document has been printed
Thread 4: PrintQueue: Printing a Job during 7 seconds
Thread 4: The document has been printed
Thread 2: PrintQueue: Printing a Job during 5 seconds
Thread 9: PrintQueue: Printing a Job during 8 seconds
Thread 2: The document has been printed
Thread 9: The document has been printed
Thread 6: PrintQueue: Printing a Job during 4 seconds
Thread 6: The document has been printed
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构