Java uses executor (executor) to manage threads

Source: Internet
Author: User
Tags volatile

I. A class that implements the Runnable interface
classMyThreadImplementsrunnable{Private Static intnum = 0; @Override Public voidrun () { while(true){            synchronized(MyThread.class){                ++num; Try{Thread.Sleep (500); } Catch(Exception e) {System.out.println (e.tostring ()); } System.out.println (Thread.CurrentThread (). GetName ()+ " " +num); }        }    }}
1. Newcachedthreadpool () method

Cachethreadpool will create a thread for each task. A very common scenario is that a single executor is used to create and manage tasks in the system. The shutdown () method prevents new tasks from being submitted to this executor. If a new task is submitted after the shutdown () method, a Java.util.concurrent.RejectedExecutionException exception is thrown.

 Public class main{    publicstaticvoid  Main (string[] args) {          = executors.  Newcachedthreadpool();            for (int i=0; i<5; + +i)              exes.execute (new  MyThread ());          Exes.shutdown ();              }}
2.FixedThreadPool () method

Fixedthreadpool uses a prioritized set of threads to perform the submitted tasks. With it, you can pre-execute expensive thread allocations at once. That is, if the maximum number of threads set is x and the number of threads committed is Y, then the corresponding threads (Y-X) will not execute until the previous X threads have finished executing.

In the following example, thread 61 does not have a chance to execute. Because while (true) is in the run () method, you can remove the while (true) and execute the 6th thread only after the first 5 threads have finished executing.

 Public class main{    publicstaticvoid  Main (string[] args) {          = executors.  Newfixedthreadpool(5);            for (int i=0; i<6; + +i)                  exes.execute (new  MyThread ());          Exes.shutdown ();              }}
3.newSingleThreadExecutor () method
 Public class main{    publicstaticvoid  Main (string[] args) {                  = executors.  Newsinglethreadexecutor();            for (int i=0; i<5; + +i)              exes.execute (new  MyThread ());          Exes.shutdown ();    }

Singlethreadexecutor is like a fixedthreadpool with a number of threads of 1. This is useful for things you want to run continuously in another thread (long-lived tasks). If you want Singlethreadexecutor to submit multiple tasks, these tasks will be queued, each task will end before the next task starts , and all tasks would use the same thread.

Two. A class that implements the Callable<e> interface (the return value is generated from the task)
classMyThreadImplementsCallable<string>{    Private Static intnum = 0; @Override PublicString Call ()throwsException { for(inti=0; i<5; ++i) {            synchronized(MyThread.class){                ++num; Thread.Sleep (200); System.out.println (Thread.CurrentThread (). GetName ()+ " " +num); }        }        returnThread.CurrentThread (). GetName () + "success!"; }}
1.executorservice.submit () method
 Public classmain{ Public Static voidMain (string[] args) {Executorservice exes=Executors.newcachedthreadpool (); ArrayList<Future<String>> RETs =NewArraylist<future<string>>();  for(inti=0; i<5; ++i) Rets.add (Exes.submit (NewMyThread ()));  for(future<string>fs:rets) {            Try{System.out.println (Fs.get ()); } Catch(interruptedexception e) {e.printstacktrace (); } Catch(executionexception e) {e.printstacktrace (); }         }    }}

Submit () will produce a future object, which is parameterized with the specific type of callable return result. You can call the future Isdone () method to query whether the future has completed. Call the Future's Get () method to get the result of the final thread's execution. In addition, the Get () method of the future is a blocking method until the result is ready .

Three. Priority of Threads
classMyThreadImplementsrunnable{Private intPriority ;  PublicMyThread () {} PublicMyThread (intPriority ) {         This. Priority =Priority ; }        Private Static intnum = 0; Private volatile DoubleD; @Override Public voidrun () { thread.currentthread (). SetPriority (priority);  while(true){             for(inti=0; i<100000; ++i) {D+ = (MATH.PI+MATH.E)/(Double) I; if(i%1000 = = 0) Thread.yield (); }            synchronized(MyThread.class){                ++num; Try{Thread.Sleep (500); } Catch(Exception e) {System.out.println (e.tostring ()); } System.out.println (Thread.CurrentThread (). GetName ()+ " " +num); }        }    }} Public classmain{ Public Static voidMain (string[] args) {Executorservice exes=Executors.newcachedthreadpool ();  for(inti=0; i<5; ++i) Exes.execute (NewMyThread (thread.min_priority)); Exes.execute (NewMyThread (thread.max_priority));    Exes.shutdown (); }}

Volatile variables ensure that the compiler does not perform any optimizations on loops, and if you do not add these operations, you will not see the effect of setting the thread priority. Mathematical operations can be interrupted, and printing to the console cannot be interrupted. The plan is long enough, so the thread scheduling mechanism comes in and intervenes, swapping tasks and focusing on priorities, and the highest priority is the preferred choice.

Four. Background threads
classSimpledaemonsImplementsrunnable{@Override Public voidrun () { while(true){            Try{TimeUnit.MILLISECONDS.sleep (200);            System.out.println (Thread.CurrentThread (). GetName ()); } Catch(interruptedexception e) {System.out.println (Thread.CurrentThread (). GetName ()+ ": interruptexception!");            E.printstacktrace (); }        }    }} Public classmain{ Public Static voidMain (string[] args)throwsinterruptedexception{ for(inti=0; i<10; ++i) {Thread Daemon=NewThread (Newsimpledaemons ()); Daemon.setdaemon (true);         Daemon.start (); } System.out.println ("All daemons started"); TimeUnit.MILLISECONDS.sleep (1000); }}

A background thread is a thread that provides a common service in the background while the program is running, and this thread is not an integral part of the program. Therefore, when all non-background threads end, the program terminates and kills all the background threads in the process. Conversely, the program will not terminate as long as any non-background threads are still running.

By customizing your own threadfactory, you can customize the properties of threads created with executor (background, priority, name)

class Implements threadfactory{    @Override    public  Thread newthread (Runnable r) {        new Thread (r);        T.setdaemon (true);         return t;    }}
classDaemonfromfactoryImplementsrunnable{@Override Public voidrun () {Try{TimeUnit.MILLISECONDS.sleep (100);        System.out.println (Thread.CurrentThread (). GetName ()); } Catch(interruptedexception e) {e.printstacktrace (); }    }} Public classmain{ Public Static voidMain (string[] args)throwsinterruptedexception{Executorservice EXEs= Executors.newcachedthreadpool (Newdaemonthreadfactory ());  for(inti=0; i<5; ++i) Exes.execute (Newdaemonfromfactory ()); System.out.println ("All Daemos started!"); TimeUnit.MILLISECONDS.sleep (1000); }}

Java uses executor (executor) to manage threads

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.