Java Interview 09| Multithreading

Source: Internet
Author: User
Tags thread class volatile

15 Top Java multithreaded questions and answers http://ifeve.com/15-java-faq/

1, about the state of the thread and mutual conversion

(1) Join () method: Enables the thread to execute sequentially. You can divide a task into subtasks, call the Join () method, wait for those subtasks to complete the operation, and then summarize the results. It is important to note that this does not guarantee the end order of each subtask thread.

(2) thread can only be from the Ready state (runnable) This unique path to the running state (running)

(3) The thread class, which defines a number of column-manipulation functions. For example, sleep () Hibernate, interrupt () interrupt, getName () get thread name, etc.

(4) the Start () method is called when the thread is started, and repeated calls throw a thread-state exception. Calling run () is equivalent to calling the normal method

(5) The thread calls the Wait () method to enter the blocking state, and the code after the Wait () method continues to execute when it wakes up again

(6) Wait () releases the lock, and yield () and sleep () do not release the lock

(7) Note that the interrupt () method is called after the state is locked by waiting for blocked to enter the lock blocked, which needs to be handled in a fair lock in Aqs.

2. Several methods of thread interruption

(1) public void interrupt () interrupt target thread

(2) Public boolean isinterrupted () returns the interrupt state

(3) public static Boolean interrupted () static method, clears the interrupt state and returns the previous value

The blocking library method, Thread.Sleep () and object.wait (), and so on, will check when the thread is interrupted, and when the interrupt is found, the actions they perform when the response is interrupted include: clear the interrupt state, throw the Interruptedexception, Indicates that the blocking operation ended prematurely because of an outage.

Can be summarized under:

(1) thread in blocked state: Clears the interrupt state, throws Interruptedexception, indicates that the blocking operation ended prematurely due to an interruption

(2) When in runnable or running state, the interrupt token of the thread is set to True

(3) No action occurs when in dead state

The above topics must be seen, I have selected here and supplemented several topics:

3, if there are Thread1, Thread2, Thread3, Thread4 four threads respectively statistics C, D, E, f four disk size, all threads are counted to THREAD5 thread to do summary, how should be realized?

The separate computing tasks are included in a single unit of work, eliminating the need to start new threads for each unit . It is often more efficient to handle multithreaded code. Because you do not have to start the thread thread separately for each compute unit. The thread that executes the code is reused.

(1) Tasks

Callable represents a piece of code that can be called and returned results

The future interface is used to represent the asynchronous task, which is the result of a task that has not yet been completed. The main methods are get (), Cancel (), and Isdone ()

Futuretask is a common implementation of the future interface, it also implements the Runnable interface, so as runnable and callable, can be the height of the performer.

(2) The performer obtains one of the many performers through the factory method of the Executors class

There is a good example of Futuretask, as follows:

public class Futuretaskexample {public static void main (string[] args) {mycallable callable1 = new Mycall                       Able (1000);            Task to perform mycallable callable2 = new Mycallable (2000); futuretask<string> FutureTask1 = new futuretask<string> (callable1);// Encapsulates a callable-written task into a Futuretask object that is dispatched by the performer futuretask<string> FutureTask2 = new Futuretask<string> (callabl             E2);        Executorservice executor = Executors.newfixedthreadpool (2);  Creates a thread pool and returns Executorservice instance Executor.execute (FUTURETASK1);                       Implementation of Task Executor.execute (FUTURETASK2);                      while (true) {try {if (Futuretask1.isdone () && Futuretask2.isdone ()) {//two tasks are complete                      System.out.println ("Done");                          Executor.shutdown ();                  Turn off the thread pool and service return; } if (!futuRetask1.isdone ()) {//Task 1 is not completed and will wait until the task is completed System.out.println ("FutureTask1 output=" +futuretask1.get ());                  } System.out.println ("Waiting for FutureTask2");                  String s = Futuretask2.get (200L, timeunit.milliseconds);                  if (s!=null) {System.out.println ("FutureTask2 output=" +s); }} catch (Interruptedexception |              Executionexception e) {e.printstacktrace ();   }catch (TimeoutException e) {//do Nothing}}}

  

Examples are as follows:

public class Sums {//Use callable more advantageous than runnable is that callable can have an exact return value. Static Class Sum implements Callable<long> {Private final long from;private final long to; Sum (long from, long to) {This.from = From;this.to = to;} @Overridepublic Long Call () {long ' acc = 0;for (long i = from; I <= to; i++) {acc = acc + i;} return ACC;}} public static void Main (string[] args) throws Exception {Executorservice executor = Executors.newfixedthreadpool (2);//Ex Ecutes the given tasks, returning a list of Futures holding their status and results when all Completelist<future<lo ng>> results = Executor.invokeall (aslist (new sum (0), new sum (+, 1_000), new sum (10_000, 1_000_000));//Another Be aware that the executor service must be shut down. If it is not closed, the JVM will not exit after the main method executes because there is still an activation thread present executor.shutdown (); for (future<long> result:results) {//Waits if necessary for the computation to complete, and then retrieves its result. System.out.println (Result.get ());}}} 

There are three points to note when writing the procedure:

(1) Callable is an interface, we need to override the method for call ()

(2) thread pool must be shutdown ()

4. 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) Must see HTTP://WWW.JIANSHU.COM/P/87BFF5CC8D8C

(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 09| Multithreading

Related Article

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.