This article is a summary of the study of the article on the network, thank you for your selfless sharing.
Java provides additional mechanisms for synchronizing blocks of code. It is more powerful and flexible than the synchronized keyword. The Lock interface provides additional functionality over the Synchronized keyword. When you use lock, be aware that you want to release the lock lock.
Package Chapter2;import java.util.concurrent.locks.lock;import java.util.concurrent.locks.reentrantlock;/* * print queue */ public class PrintQueue {private final Lock Queuelock = new Reentrantlock ();p ublic void PrintJob (Object document) {Queueloc K.lock ();//Get control of the lock object try {Long duration = (long) (Math.random () *10000); System.out.println (Thread.CurrentThread (). GetName () + "printqueue:printing a Job during" + (duration/1000) + "seconds") ; Thread.Sleep (duration);} catch (Exception e) {e.printstacktrace ();} finally{queuelock.unlock ();//release control of Lock Object}}}
Package Chapter2;public class Job implements Runnable{private PrintQueue printqueue;public Job (PrintQueue PrintQueue) { This.printqueue = PrintQueue;} @Overridepublic 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 chapter2;/** * * <p> * Description: Sync code block with lock * </p> * @author Zhangjunshuai * @version 1.0 * Cr Eate date:2014-9-16 pm 4:57:06 * Project name:java7thread * * <pre> * Modification History: * Date Auth or Version Description *-------------------------------------------------------------------------- --------------------------------- * Lastchange: $Date:: $ $Author: $ $Rev: $ * </pre> * * /public class Main5 {/** * <p> * </p> * @author Zhangjunshuai * @date 2014-9-16 pm 4:57:00 * @param args */publ IC 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 ();}}}
Java Concurrency Learning 14-using lock to synchronize code blocks