Java多线程之~~~Lock接口和ReentrantLock的使用

在多线程开发中,除了synchronized这个关键字外,我们还能通过Lock接口来实现这种效果。通过Lock接口来实现

这种多线程加锁效果的好处是非常的灵活,我们不在需要对整个函数加锁,而且可以很方便的把他放在我们函数的任何

一个地方,非常的称心,而且从效率上来说,使用Lock接口要比使用synchronized关键字效率高一些,下面我们来使用

一个例子来说明这种方法的使用。


package com.bird.concursey.charpet3;

public class Job implements Runnable {

	private PrintQueue printQueue;

	public Job(PrintQueue printQueue) {
		this.printQueue = printQueue;
	}

	@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());
	}

}


package com.bird.concursey.charpet3;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintQueue {
	
	private final Lock queueLock = new ReentrantLock();
	
	public void printJob(Object document) {
		queueLock.lock();
		Long duration=(long)(Math.random() * 10000);
		System.out.println(Thread.currentThread().getName()+ ":PrintQueue: Printing a Job during "+(duration/1000)+" seconds");
		try {
			Thread.sleep(duration);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			queueLock.unlock();
		}
	}
	
	public static void main(String[] args) {
		PrintQueue printQueue = new PrintQueue();
		Thread thread[] = new Thread[10];
		for(int i = 0; i < 10; i++) {
			thread[i] = new Thread(new Job(printQueue), "Thread " + i);
		}
		for(int i = 0; i < 10; i++) {
			thread[i].start();
		}
	}
}


  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
下面是一个简单的Java线程示例,使用Lock接口实现线程同步: ```java import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ThreadSyncExample { private Lock lock = new ReentrantLock(); // 创建Lock接口的实例 private int count = 0; public void increment() { lock.lock(); // 线程获取锁 try { count++; } finally { lock.unlock(); // 释放锁 } } public void decrement() { lock.lock(); // 线程获取锁 try { count--; } finally { lock.unlock(); // 释放锁 } } public int getCount() { return count; } public static void main(String[] args) throws InterruptedException { ThreadSyncExample example = new ThreadSyncExample(); Thread t1 = new Thread(() -> { for (int i = 0; i < 100000; i++) { example.increment(); // 每次增加1 } }); Thread t2 = new Thread(() -> { for (int i = 0; i < 100000; i++) { example.decrement(); // 每次减少1 } }); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Count: " + example.getCount()); // 输出最终结果 } } ``` 在上面的示例中,我们创建了一个`ThreadSyncExample`类,其中包含了一个`Lock`接口的实例`lock`,以及一个`count`变量。`increment()`方法和`decrement()`方法分别用于增加和减少`count`变量的值,这两个方法都使用`lock`来实现线程同步。最后,我们创建了两个线程`t1`和`t2`,分别执行`increment()`方法和`decrement()`方法,最后输出最终的`count`值。 需要注意的是,在使用`Lock`接口时,一定要在`try`块中获取锁,在`finally`块中释放锁,以确保在任何情况下都能正确释放锁。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值