java multithreading --- several ways to create a thread

Several ways to create a thread

  In concurrent programming, a thread is created, we often do, so generally speaking, there are four ways to create threads:

  1, inheritance Thread class.

  2, to achieve Runnable interface.

  3, implement Callable interface FutureTask used in combination.

  4, be implemented using a thread pool mode.

 

Inheritance Thread to create threads

public class ThreadTest1 extends Thread {
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("ThreadTest1 is running");
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadTest1 threadTest1=new ThreadTest1();
        threadTest1.start();
        System.out.println ("First:" + System.currentTimeMillis ()); 
        the Thread.sleep ( 1000 ); 
        threadTest1.run (); 
        System.out.println ( "Second:" + System.currentTimeMillis ()); 
    } 
}
Implementation of the results: 

First: 1,569,155,515,336 
ThreadTest1 IS running 
ThreadTest1 IS running 
second: 1569155517338

  As can be seen from the above example, calling threadTest1.start () when the output time of the first thread of execution and then executed in the output statement, call threadTest1.run () method is executed first ThreadTest1 the run () method after performing the actual statement output the main thread, so you can draw a direct call to run () method is not the way to start a thread, but directly in the calling thread run () method and thread has nothing to do, start a thread way is to call Thread.start ()method.

Implement Runnable interface to create threads

public class ThreadTest2 implements Runnable {
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread is running");
    }

    public static void main(String[] args) {
        ThreadTest2 threadTest2=new ThreadTest2();
        Thread thread=new Thread(threadTest2);
        thread.start();
        System.out.println(System.currentTimeMillis());
    }
}

  Implement the interface Runnable to create a thread is an implementation, unlike the inheritance Thread class to create a thread that is a succession, one is the implementation of the interface, due JAVA does not allow multiple inheritance, so to achieve Runnable interface in real-world projects to create a thread mode or use more of.

 

Implement Callable Interface

 

public class ThreadTest3 implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int i = 0;
        for (; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
        System.out.println(Thread.currentThread().getName() + " " + i);
        return i;
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadTest3 threadTest3 = new ThreadTest3();
        //很重要,无论多少个线程调用futureTask,futureTask只会执行一次
        FutureTask<Integer> futureTask = new FutureTask<Integer>(threadTest3);
        Thread thread1 = new Thread(futureTask, "aa");
        Thread thread2 = new Thread(futureTask, "bb");
        Thread thread3 = new Thread(futureTask, "cc");
        thread1.start();
        Thread.sleep(3000);
        thread2.start();
        Thread.sleep(3000); 
        Thread3.start ();
        the try { 
            System.out.println ( "final result" + futureTask.get ()); 
        } the catch (ExecutionException E) { 
            e.printStackTrace (); 
        } 

    } 
}

 

  Callable interface to achieve the most important thing is to get the return value of the thread execution, but the implementation class Callable interface with FutureTask need to use, but we note that the above example is very important point is that no matter how many threads will eventually be performed futuretask there is a thread of execution, so this method will be safe in the concurrent become, do not worry about multiple threads call makes an incorrect result.

 

Use the thread pool to create a thread

public class ThreadMain {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
       ExecutorService executorService= Executors.newFixedThreadPool(3);
        Callable<Integer> callable=new ThreadTest3();
        Future f=executorService.submit(callable);
        System.out.println("最终结果为" + f.get());
        executorService.shutdown();

        ExecutorService executorService2=Executors.newFixedThreadPool(3);
        Thread thread=new ThreadTest1();
        executorService2.execute(thread);
        executorService2.shutdown();
    }
}

  Use the thread pool to create a thread relies mainly on Executors static method to create a thread pool, in fact, the essence of ways to create threads or above 3 ways, but to perform the task with comparisons use multithreading in practical use many.

 

Guess you like

Origin www.cnblogs.com/rhodesis/p/11569178.html