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


    在多线程开发。除了synchronized这个keyword外,我们还通过Lock接口来实现这样的效果。由Lock接口来实现

    这样的多线程加锁效果的优点是非常的灵活,我们不在须要对整个函数加锁,并且能够非常方便的把他放在我们函数的不论什么

    一个地方,很的称心,并且从效率上来说。使用Lock接口要比使用synchronizedkeyword效率高一些,以下我们来使用

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


    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
    ", Thread
    				.currentThread().getName());
    		printQueue.printJob(new Object());
    		System.out.printf("%s: The document has been printed
    ", 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();
    		}
    	}
    }
    


    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    javascript Date format(js日期格式化)
    WebService中方法的重载
    win10 剪贴板 拒绝访问 Cannot open clipboard
    win10 剪贴板 拒绝访问
    Image Base64 Datasnap Image delphi与c#互相兼容识别
    app 支付宝 支付 alipaySdk
    Java2OP
    delphi action学习
    FireDAC 超时
    TCheckListBox
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4678568.html
Copyright © 2020-2023  润新知