java multithreading understanding and realization

 In fact, multi-threading is also well understood, like, the same aircraft through security than we take the high-speed rail through security when an entry has only one checkpoint, and multithreading is to open a number of security checkpoint, paste the code word does not say

Thread achieved in three ways:

First, create a Thread class inheritance Thread class

  1, define Thread subclass, override run () method, the thread needs to be done to put the contents of the operation method based body.

  2, create an instance of a subclass of Thread, the object of the calling thread in the instance start () method to start a thread, this method is also a method represents the number of threads when multiple threads need to start, just call repeatedly places.

Package com.thread;
 public  class FirstThreadTest the extends the Thread {
   int I = 0 ;
   // override method run, the run method is a method performed live somatic 
  public  void run () {
     for (; I <100; I ++ ) { 
      the System. Out.println (getName () + "" + I); 
    } 
  } 
  public  static  void main (String [] args) {
     for ( int I = 0; I <100; I ++ ) { 
      System.out.println (Thread.currentThread () .getName () + ": " + I);
       IF (I 20 is == ) {
        new FirstThreadTest().start();
        new FirstThreadTest().start();
} } }
}

The above code Thread.currentThread () method returns the currently executing thread object, getName () method returns the name of the thread.

 

Second, create threads through the Runnable interface class, which is commonly used as a

  1. Define runnable interface implementation class, and override the run () method, which inherits the Thread class with a run in the same

  2, create an instance of the implementation class, and create a Thread object instance, the object also represents the thread number of objects, start multiple threads only need to call multiple objects start () method places.

package com.thread;
public class RunnableThreadTest implements Runnable
{
  private int i;
  public void run()
  {
     for(i = 0;i <100;i++){
       System.out.println(Thread.currentThread().getName()+" "+i);
     }
  }
  public static void main(String[] args){
    for(int i = 0;i < 100;i++){
      System.out.println(Thread.currentThread().getName()+" "+i);
      if(i==20){
        RunnableThreadTest rtt = new RunnableThreadTest();
        new Thread(rtt,"新线程1").start();
        new Thread(rtt,"新线程2").start();
      }
    }
  }
}

Third, to achieve multi-thread by thread pool, this is to do common and most practical

   1, by ExecutorService to manage the thread pool, and the number of initialize the thread

   2, define a queue to hold the thread pool

   3, to determine whether the thread execution cycle or sleep

Import java.util.Queue;
 Import java.util.concurrent.ConcurrentLinkedDeque;
 Import java.util.concurrent.ExecutorService;
 Import java.util.concurrent.Executors; 

public  class TestThread { 

    // first initialize the thread pool ExecutorService for multi-management threads, the number of threads provided 
    Private  static ExecutorService = Executors.newFixedThreadPool the pool (50 ); 
    
    // define queue queue, used to store the thread pool, thread object is the Runnable 
    Private  static queue <the Runnable> queue = new new ConcurrentLinkedDeque <> (); 
    
    // class loading multithreaded 
    static { 
        ( new new TestThread ()).new new ThreadPoolInvoke () Start ();. 
    } 
            
    Private   class ThreadPoolInvoke the extends the Thread { 
        @Override 
        public  void RUN () {
             // infinite loop queue has been determined 
            the while ( to true ) {
                 the try {
                     // If empty, the thread to sleep for three seconds 
                    IF ( queue.isEmpty ()) { 
                        the Thread.sleep ( 1000 *. 3 ); 
                    } 
                    // if not empty then performing tasks, defining excute method 
                    excute (); 
                } the catch(Exception E) {
                     // the TODO: handle Exception 
                } 
                
            } 
        } 
    
    } 
    / ** 
     * Set the thread queue to method 
     * @param Runnable
      * / 
    public  static  void the setTask (the Runnable Runnable) { 
        queue.add (Runnable); 
    } 
    
    / ** 
     * task execution thread 
     * / 
    Private  void excute () {
         // to ensure the security thread, where you can set the synchronization lock, this indicates that the current entrants
         // the synchronized (the this) {
         // get queue queue size     
        int curLen = queue.size ( );
        for ( int I = 0; I <curLen; I ++ ) {
             // poll method showing removing the first element from the queue 
            the Runnable Item = queue.poll ();
             // then subject to the multi-threaded processing         
            pool.execute ( Item); 
        } 
        // } 
    } 
}

Well, today's multi-threaded on to share it, whether or not learn of it?

Guess you like

Origin www.cnblogs.com/yonim/p/11417598.html