Java interview 41-45| concurrency and Locks

Source: Internet
Author: User

41. The difference between synchronized and lock

There are some drawbacks to synchronizing blocks that are implemented using the SYNCHRONIZED keyword:

(1) There is only one type of lock

(2) thread gets locked or blocked

(3) lock is implemented in the Java language level based on the CAS spin mode to achieve the lock, under the concurrency conditions, its performance is relatively better than synchronized.

In order to solve the various problems, a more complex lock-thread locking was proposed later. The thread lock can be improved in several ways:

(1) Adding different types of locks, such as read locks and write locks (the primary implementation class is the Reentrantreadwritelock Class)

(2) There is no limit to the blocking of the lock, that is, it can be locked in one method and unlocked in another method.

Because Semaphore does not associate a license with a particular thread, the license obtained in one thread can be freed from another thread.

(3) If a thread does not get a lock, such as a lock held by another thread, it allows the thread to go back or continue, or do something else. such as using Trylock () and Trylock (Long,timeunit). When you find that an attempt to lock cannot be added, you can first release the lock that has been successfully added to the other objects, and then try again later to avoid deadlocks to some extent.

(4) Allow the thread to attempt to lock and discard after the wait time has passed.

The Reentrantlock implements the lock interface and provides the same mutex and memory visibility as the synchronized. When getting/exiting Reentrantlock, there is the same memory semantics as the Enter/exit synchronization code block. The locking semantics are also available for re-entry.

Reentrantlock has added some advanced features compared to synchronized, with 3 main items:

(1) waiting to be interrupted

(2) can achieve a fair lock (synchronized implementation of the non-fair lock)

(3) A lock can bind multiple conditions (one reentrantlock can bind multiple condition objects at the same time

Reentrantlock gets locked with three ways:
A) lock (), if the lock is acquired immediately and returns if another thread holds the lock, the current thread is dormant until the lock is acquired

b) Trylock (), if acquired the lock immediately returns true if another line is impersonating holds the lock, returns false immediately

c) Trylock (long timeout,timeunit unit) If the lock is acquired immediately returns true if another line is impersonating holds the lock, waits for the parameter given the time, in the process of waiting, if the lock is acquired, returns true if the wait timeout, Returns false

d) lockinterruptibly: If acquired lock is returned immediately, if no lock is acquired, the current thread is dormant until either locked, or when the thread is interrupted by other threads

42. Analysis of the implementation principle of thread pool and task scheduling process

The implementation principle of the thread pool can be referenced as follows:

(1) http://blog.csdn.net/mazhimazh/article/details/19243889

(2) http://blog.csdn.net/mazhimazh/article/details/19283171

(3) Refer to "Java Commando" 295 page Content

The thread pool implementation principle is the combination of thread pooling and work queue, which is embodied in the Executor task execution framework.

A simple little example.

Package Threadpool;import java.util.linkedlist;import java.util.list;/** * thread pool class, threading Manager: Create threads, perform tasks, destroy threads, get thread basic information */  Public final class ThreadPool {//The number of default threads in the thread pool is 5private static int worker_num = 5;//worker thread Private workthread[] workthrads;// Unhandled task private static volatile int finished_task = 0;//task queue, as a buffer, List thread unsafe private list<runnable> Taskqueue = new Linkedlist<runnable> ();p rivate static ThreadPool threadpool;//Create a thread pool with the number of default threads private ThreadPool () {this (5);} Create a thread pool, Worker_num is the number of worker threads in the thread pools private ThreadPool (int worker_num) {threadpool.worker_num = Worker_num;workthrads = new workthread[worker_num];for (int i = 0; i < Worker_num; i++) {workthrads[i] = new Workthread (); Workthrads[i].start ();// Turn on thread in thread pool}}//single mode, get a thread pool with a default number of threads public static ThreadPool Getthreadpool () {return Getthreadpool (threadpool.worker_ num);} Single mode, gets a thread pool with a specified number of threads, Worker_num (>0) creates the default number of worker threads for the number of worker threads in the thread pools//worker_num<=0 public static ThreadPool Getthreadpool (int worker_num1) {if (worker_num1 <= 0) worker_NUM1 = threadpool.worker_num;if (ThreadPool = = null) ThreadPool = new ThreadPool (WORKER_NUM1); return ThreadPool;} To perform a task, actually just add the task to the task queue, and when to execute the thread pool manager, the public void execute (Runnable task) {synchronized (taskqueue) {Taskqueue.add (Task ); Taskqueue.notify ();}} In order to execute a task in bulk, you simply add the task to the task queue, and when to execute the thread pool manager, the public void execute (runnable[] task) {synchronized (taskqueue) {for (Runnable T: Task) Taskqueue.add (t); taskqueue.notify ();}} In order to perform a task in bulk, you simply add the task to the task queue and when to execute the thread pool manager, the public void execute (list<runnable> task) {synchronized (taskqueue) { Runnable t:task) Taskqueue.add (t); taskqueue.notify ();}} Destroys the thread pool, which guarantees that all threads are destroyed if all tasks are completed, otherwise the public void destroy () {while (!taskqueue.isempty ()) {///If there is a task not completed is not destroyed until the task is completed. Just go to sleep. try {thread.sleep);} catch (Interruptedexception e) {e.printstacktrace ()}} The worker thread stops working and is set to nullfor (int i = 0; i < Worker_num; i++) {workthrads[i].stopworker (); workthrads[i] = null;} Threadpool=null;taskqueue.clear ();//emptying the task queue}//returns the number of worker threads public int Getworkthreadnumber () {return worker_Num;} Returns the number of completed tasks, where the completion is only the number of tasks out of the task queue, possibly the task does not actually perform the completion of the public int getfinishedtasknumber () {return finished_task;} Returns the length of the task queue, which is the number of tasks that have not yet been processed public int getwaittasknumber () {return taskqueue.size ();} Override the ToString method to return thread pool information: number of worker threads and number of completed tasks @overridepublic String toString () {return ' Workthread #: "+ worker_num +" fin ished Task Number: "+ finished_task +" Wait task number: "+ Getwaittasknumber ();} /** * Inner class, worker thread */private class Workthread extends Thread {//The worker thread is valid to end the worker thread Private Boolean isrunning = true;/* * key Ah, if the task queue is not empty, then remove the task execution, if the task queue is empty, then wait */@Overridepublic void Run () {Runnable R = null;while (isrunning) {//note, if the thread is invalid, the Run method will end naturally, The thread is useless synchronized (taskqueue) {///here is provided synchronous while (IsRunning && taskqueue.isempty ()) {//queue is empty try { Taskqueue.wait (20);} catch (Interruptedexception e) {e.printstacktrace ();}} if (!taskqueue.isempty ()) R = taskqueue.remove (0);//Remove Task}if (r! = null) {R.run ();//Perform task}finished_task++;r = NULL;}} End run//stops working so that the thread naturally finishes executing the Run method and ends naturally with the public void Stopworker () {IsRunning = false;}}} 

Test thread pool Public  class Testthreadpool {public static void main (string[] args) {//Create thread pool for 3 threads ThreadPool t = threadpool.ge  Tthreadpool (3); T.execute (new runnable[] {New Task (), new Task (), New Task ()}), T.execute (new runnable[] {New Task (), new Task (), New Task ()}); System.out.println (t); T.destroy ();//All threads execute destorySystem.out.println (t);} Task classes Static class task implements Runnable {private static volatile int i = 1; @Overridepublic void Run () {//Execute task SYSTEM.O UT.PRINTLN ("task" + (i++) + "Finish");}}}

The scheduling of Java threads is divided into collaborative thread scheduling and preemptive thread scheduling.

Schedulethreadpoolexecutor is a multithreaded scheduler provided by Java that can receive tasks and schedule them to thread constructor threads. Here are some things to consider:

"Java Commando" page 306

Multi-thread and task resource sharing are used to realize the scheduling of large-volume tasks on the server.

Java interview 41-45| concurrency and Locks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.