These days began to learn the contents of Java multithreading concurrent programming, but also learned the knowledge of multithreading, but always feel that the learning is not very clear; I hope this time to learn "Java programming ideas" can make their own concurrency, multithreading concept has a more in-depth understanding. This chapter is estimated to write several blogs, this blog is a summary of the foundation, the main content is to start a thread of several ways and the thread some operation function summary.
First of all, to understand the concept of multithreading, multithreading seems to be running multiple tasks at the same time, but from the operating system level just let multiple tasks at a very fast speed switch, a moment is actually only one task on the CPU run. Multithreading in Java is implemented by the thread class, and we give the task to the thread class object, and then it runs our task in a multithreaded fashion. There is a run () function in the thread class that puts the tasks we need to perform in the body.
We can have three ways to start a thread. The first is the direct inheritance of the thread class, the implementation of the inside of the Run () method, this method is the simplest, but this can no longer inherit another class. The second method is to implement the Runnable interface, we also need to implement the run () method inside, but now it still does not have any threading capability, to implement threading behavior, you must display a task attached to the thread on the implementation, Specifically, a Runnable object is passed to a thread object. The third method is to implement the callable interface, the content of this interface and the Runnable interface is not different, the difference is that the callable interface can have a return value, we can explicitly capture this return value.
/// implement a thread class by inheriting thread Public class firstthread extends Thread{ Private intI Public void Run(){ for(intI=0;i<Ten; i++) {///getname () is a method of the thread class because it inherits the thread class /// so you can call directlySystem.out.println (GetName () +" "+i); } } Public Static void Main(string[] args) { for(intI=0;i<Ten; i++) {//General conditions can be obtained by thread.currentthread the current threadSystem.out.println (Thread.CurrentThread (). GetName () +" "+i);if(i==1) {Executorservice exec = Executors.newcachedthreadpool (); Exec.execute (NewFirstthread ());//Add a new taskExec.shutdown ();/// prevent new tasks from being added in the back} } }/*output main 0 main 1 main 2 Thread-0 0 Thread-0 1 Thread-0 2 Thread -0 3 Thread-0 4 Thread-0 5 Thread-0 6 Thread-0 7 Thread-0 8 Thread-0 9 ma In 3 main 4 main 5 main 6 main 7 main 8 main 9 * /}
PackageLKL;ImportJava.util.concurrent.ExecutorService;ImportJava.util.concurrent.Executors;//Implement a thread class by implementing a Runnable interface Public class secondthread implements Runnable{ Private intI///also implement the Run () method Public void Run(){ for(intI=0; i<Ten; i++) {System.out.println (Thread.CurrentThread (). GetName () +" "+i); } } Public Static void Main(string[] args) { for(intI=0;i<Ten; i++) {System.out.println (Thread.CurrentThread (). GetName () +" "+i);if(i==1) {Executorservice exec = Executors.newcachedthreadpool (); Exec.execute (NewThread (NewSecondthread (),"New Thread 1")); Exec.shutdown (); } }/ * Main 0 main 1 pool-1-thread-1 0 pool-1-thread-1 1 pool-1-thread-1 2 pool- 1-thread-1 3 pool-1-thread-1 4 pool-1-thread-1 5 pool-1-thread-1 6 pool-1-thread-1 7 PO OL-1-THREAD-1 8 Pool-1-thread-1 9 main 2 main 3 main 4 main 5 main 6 main 7 Main 8 Main 9 * /}}
Package LKL;//Implement thread classes by inheriting callable interfaces//callable interface and Futuretask interface mating use//We use Futuretask to encapsulate the callable and then//You can get the return value of the thread through the Futuretask object,/// In this case, the exception thrown by the thread can also be caught. //Note: These two classes have generic restrictions, and the exact type is the same as the return value of the call () methodImport Java.util.concurrent.callable;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.FutureTask; Public classThirdthread Implements callable<integer>{Private intI ///Implement Call () method as thread execution body PublicIntegerPager(){ for(i=0;i<Ten; i++) {System. out. println (Thread.CurrentThread (). GetName () +" "+i); }returnI } Public Static void Main(string[] args) {Thirdthread RT =NewThirdthread ();//Use Futuretask to wrap callable objectsfuturetask<integer> task =NewFuturetask (RT); for(intI=0; i<Ten; i++) {System. out. println (Thread.CurrentThread (). GetName () +" "+i);if(i==1) {Executorservice exec = Executors.newcachedthreadpool (); Exec.execute (Task); Exec.shutdown (); } }Try{//Gets the thread return value and, if the thread has not finished executing, blocks until the return value is obtainedSystem. out. println ("The return value of the thread:"+task.Get()); }Catch(Exception ex) {Ex.printstacktrace (); } }/ * Main 0 main 1 pool-1-thread-1 0 pool-1-thread-1 1 pool-1-thr Ead-1 2 pool-1-thread-1 3 main 2 main 3 main 4 main 5 ma In 6 main 7 main 8 main 9 pool-1-thread-1 4 pool-1-thread-1 5 Pool-1-thread-1 6 pool-1-thread-1 7 pool-1-thread-1 8 pool-1-thread-1 9 The return value of the thread: Ten */}
Then in the code above we see a Executor object, which is explained below: Executor (executor) is a class that manages the thread object from Java5, and the Executor object provides a hierarchy between the client and the task execution The task is performed by this mediation object, unlike the client's direct execution of the task. Executor allows you to manage the execution of an asynchronous task without displaying the lifecycle of the management thread. The specific step is to create a Executorservice object, and then put the thread into this object to run, the corresponding Executorservice object three kinds: First, the previous Cachedthreadpool, will create in the program with the required number of threads. The second is Fixedthreadpool, which can create a specified number of threads at once (by specifying the number of implementations in the constructor). The third is singlethreadexecutor, which executes only one thread at a time, and if multiple tasks are submitted to it, the tasks are queued and executed sequentially.
Here is a brief introduction to several methods of controlling threads (functions)
(1). Join () method
The join () method means that one thread waits for another thread. If I call T.join () on the current thread, the front thread will block until the T thread is finished, and the join () has an overloaded method to specify the time to block.
PackageLKL;use of the///join () method Public class jointhread extends Thread{ Public Jointhread(String name) {Super(name); } Public void Run(){ for(intI=0;i<Ten; i++) {System.out.println (GetName () +" "+i); } } Public Static void Main(string[] args)throwsexception{ for(intI=0; i<Ten; i++) {if(i==1) {Jointhread JT =NewJointhread ("Threads to be join"); Jt.start ();//main thread called the Join () method of the JT thread, the main thread //The main thread will not continue until after JT finishesJt.join (); } System.out.println (Thread.CurrentThread (). GetName ()); } }}
(2). Setdaemon (True) method
This method means that the current line is Cheng as a background thread. A background thread runs in the background, and its task is to provide services to other threads (such as the JVM's garbage collection mechanism, which is a typical background thread). Background threading is characterized by the fact that if all foreground threads are dead, the background thread will die automatically.
PackageLKL; Public class daemonthread extends Thread{ Public void Run(){ for(intI=0;i<Ten; i++) {System.out.println (GetName () +" "+i); } } Public Static void Main(string[] args)throwsexception{Daemonthread dt =NewDaemonthread (); Dt.setdaemon (true);//Set as background thread and need to be provisioned before startingDt.start (); for(intI=0; i<Ten; i++) {System.out.println (Thread.CurrentThread (). GetName () +" "+i); }//You can see that after the main thread ends, the daemon thread also ends}}
Package Lkl;import java.util.concurrent.*;The //background thread will not execute the FINALLY clause//will terminate its run () method class Adaemon implements Runnable{ Public voidRun () {Try{System.out.println ("Starting Adamon"); TimeUnit.SECONDS.sleep (1); }Catch(Interruptedexception e) {System.out.println ("Err"); }finally{System.out.println ("This should always run?"); } }} Public class daemonsdontrunfinally { Public Static voidMain (string[] args) {Thread T =NewThread (NewAdaemon ()); T.setdaemon (true); T.start (); }}
(3). Thread Sleeping Sleep ()
The function of sleep () is simple, simply to let the currently executing thread for a period of time (we can specify this time) and into the blocking state. Sleep () is a static method of the thread class.
(4). Thread Concession yield ()
Yield () is a bit similar to sleep () and also lets the currently executing thread pause, but it does not block the current thread, but instead gets it into a ready state. Then, in a single dispatch, a thread with the same priority or higher is taken to execute. The note is that yield () is only a suggested method, it does not fully guarantee the current thread concessions, so we should more use sleep () instead of yield ().
(5). SetPriority () Change the priority of a thread
The higher the priority of the line Cheng Qi the greater the chance of execution, but it is dependent on the specific operating system, and the level of prioritization of different operating systems is different. So Java provides three static constants to represent the priority: Max_priority represents the highest priority. Min_priority represents the lowest priority. Norm_priority represents a general priority; If we want to prioritize threads, we should try to choose the three constants instead of the other numbers.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Thinking in Java--java multithreaded learning notes (1)