java multithreading several implementations

1. Thread class inheritance, override the run method
2. implement Runnable, override run method, an object implementation example Runnable interface implementation class constructor as target Thread
3. Create a thread through Callable and a FutureTask,
4. Create a thread pool by thread (the one already mentioned)

Two kinds of the foregoing may be attributed to a Class: None Return Value simple reason that, by rewriting the run method, the return value is run void embodiment, there is no way to return the results of 
the latter two can be attributed to a Class: returns a value, by Callable interface methods call will be realized, the return value is Object, so the results can be returned in the object Object

Option 1: Thread Thread class inheritance implementation as follows:

public  class ThreadDemo01 the extends the Thread {
     public ThreadDemo01 () {
         // write subclass constructors can default 
    }
     public  void RUN () {
         // prepare their own threaded code 
        System.out.println (Thread.currentThread (). getName ()); 
    } 
    public  static  void main (String [] args) { 
        ThreadDemo01 threadDemo01 = new new ThreadDemo01 (); 
        threadDemo01.setName ( "I custom thread. 1" ); 
        threadDemo01.start ();        
        System.out.println (Thread.currentThread () toString ().);    
    }
}

 

Program results: 
the Thread [main, 5, main] 
I was the custom thread 1

Thread implementations 2: by implementing Runnable interface, implementation instance run method, implemented as an interface class Thread a target as a parameter of the parameterized constructor Thread, by calling the start () method to start a thread

public class ThreadDemo02 {

    public static void main(String[] args){ 
        System.out.println(Thread.currentThread().getName());
        Thread t1 = new Thread(new MyThread());
        t1.start(); 
    }
}

class MyThread implements Runnable{
    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println(Thread.currentThread().getName()+"-->我是通过实现接口的线程实现方式!");
    }   
}

 

Result of the program: 
main 
the Thread-0-> I is achieved by way of a thread that implements the interface!

Thread implementations 3: created by Callable and FutureTask threads 
a: Create Callable interface implementation class, and implements Call method 
Call method to create an implementation Callable implementation class, using FutureTask packaging Callable object, which FutureTask object encapsulates Callable objects: B the return value of 
c: create a target thread object using FutureTask object and start the thread 
d: call FutureTask object get () to get the child thread execution end of the return value

public class ThreadDemo03 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Callable<Object> oneCallable = new Tickets<Object>();
        FutureTask<Object> oneTask = new FutureTask<Object>(oneCallable);

        Thread t = new Thread(oneTask);

        System.out.println(Thread.currentThread().getName());

        t.start();

    }

}

classThe Tickets <Object> the implements a Callable <Object> { 

    // override method call 
    @Override
     public Object call () throws Exception {
         // the TODO Auto-Generated Stub Method 
        System.out.println (Thread.currentThread (). GetName () + "-> I is achieved by implementing the package by FutureTask Callable Interface thread" );
         return  null ; 
    }    
}

 

Result of the program: 
main 
the Thread-0-> I is achieved by FutureTask Callable Wrapper by implementing the interface thread

Thread implementations 4: create a thread by thread pool

public class ThreadDemo05{

    private static int POOL_NUM = 10;     //线程池数量

    /**
     * @param args
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        ExecutorService executorService = Executors.newFixedThreadPool(5);  
        for(int i = 0; i<POOL_NUM; i++)  
        {  
            RunnableThread thread = New new RunnableThread (); 

            // the Thread.sleep (1000); 
            executorService.execute (Thread);   
        } 
        // close the thread pool 
        executorService.shutdown (); 
    }    

} 

class RunnableThread the implements the Runnable   
{      
    @Override 
    public  void RUN ()   
    {   
        the System .out.println ( "created by way of a thread pool thread:" + Thread.currentThread () getName () + "." );   

    }   
}  

 

Result of the program: 
the thread created by the thread pool mode: pool-1-thread-3 
threads created by thread pool mode: pool-1-thread-4 
threads created by thread pool mode: pool-1-thread-1 
through thread creates a thread pool mode: pool-1-thread-5 
threads created by thread pool mode: pool-1-thread-2 
threads created by thread pool mode: pool-1-thread-5 
created by a thread pool mode thread: pool-1-thread-1 
threads created by thread pool mode: pool-1-thread-4 
threads created by thread pool mode: pool-1-thread-3 
threads created by thread pool mode: pool-1 -thread-2

ExecutorService, Callable belong to the Executor framework. Returns a result of introducing the new thread in the JDK1.5, there Future interface framework also belongs, with this feature is very convenient to obtain a return value. 
Through the analysis can know, he is also implements Callable interface, the Call method, so there is a return value. This is exactly in line with the previously mentioned two classifications

After performing Callable task, you can get a Future object, call the get in on the object you can get to the return of the Object Callable task. get method is blocked, namely: no thread returns the result, the get method will wait.

Then introduce Executors class: provides a series of factory methods for creating a thread pool, thread pool returns have achieved ExecutorService interface.

public static ExecutorService newFixedThreadPool (int nThreads) 
thread pool that creates a fixed number of threads.
public static ExecutorService newCachedThreadPool () 
Creates a cached thread pool thread call to execute will reuse previously constructed (if the thread is available). If an existing thread is not available, a new thread is created and added to the pool. Terminate and remove those threads that have not been used for 60 seconds from the cache.
public static ExecutorService newSingleThreadExecutor () 
to create a single threaded Executor.
static ScheduledExecutorService newScheduledThreadPool public (int 
corePoolSize) 
to create a thread pool to support regular and periodic task execution, can be used to replace the Timer class in most cases.
Providing ExecutoreService submit () method, passing a Callable a, or the Runnable, return Future. If the background thread pool Executor has not calculated the Callable completed, this call returns a Future object get () method will block until the calculation is complete.

Summary:
quoted Ali's advice on the thread:

 

 

 


Original link: https: //blog.csdn.net/java_zyq/article/details/87917734

Guess you like

Origin www.cnblogs.com/diandianquanquan/p/11434037.html