Several ways to achieve multithreading

  • Inherit Thread

    advantage:

    1. Simple code, direct operation

    2. No return value, cannot inherit other classes after inheriting a class, poor scalability

      public class ThreadTest  {
          public static void main(String[] args) {
              MyThread myThread=new MyThread();
              myThread.setName("thread1");
              myThread.start();
      
              System.out.println("主线程:"+Thread.currentThread().getName());
          }
      }
      class MyThread extends Thread{
          @Override
          public void run() {
              System.out.println("run");
          }
      }
      
  • Implement the Runnable interface

    advantage:

    1. Can implement multiple interfaces and can inherit a class

    2. No return value, can not be started directly, you need to construct a Thread instance

      public class RunnableTest {
          public static void main(String[] args) {
              MyRunnable myRunnable=new MyRunnable();
              Thread thread= new Thread(myRunnable);
              thread.start();
          }
      }
      class MyRunnable implements Runnable{
      
          @Override
          public void run() {
              System.out.println("run");
          }
      }
      
  • Anonymous inner class

     public static void main(String[] args) {
		              new Thread(()->{
		                  System.out.println("run");
		              },"thread1").start();
		          }
  • Callable and FutureTask

    • Create an implementation class of the Callable interface, implement the call method, combine the FutureTask class to wrap the Callable object, and implement multithreading
    • Advantages: return value, good scalability
    public class CalAndFuture {
          public static void main(String[] args) throws ExecutionException  {
              MyTask myTask=new MyTask();
              FutureTask<Object> futureTask=new FutureTask<>(myTask);
      
              //futureTask继承了Runnable,可以放在Thread中启动执行
              Thread thread=new Thread(futureTask);
              thread.setName("thread1");
              thread.start();
      
              try {
                  System.out.println(futureTask.get());//获取返回值
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
      
          }
      }
      class MyTask implements Callable<Object>{
      
          @Override
          public Object call() throws Exception {
              System.out.println("callable");
              return "sth";
          }
      }
    
  • Create a thread through the thread pool
    Custom Runnable interface, implement the run method, create a thread pool, call the execute method and pass in the object

  • Advantages
    High security, reuse threads

    public class Pool {
        public static void main(String[] args) {
            ExecutorService executorService= Executors.newFixedThreadPool(3);
    
            for (int i = 0; i < 10; i++) {
    
            executorService.execute(new ThreadDemo());
            }
            executorService.shutdown();
        }
    }
    class ThreadDemo implements Runnable{
    
        @Override
        public void run() {
            System.out.println("ThreadPool+Runnable");
        }
    }
    

    The thread pool does not allow the use of Executors to create, but through the ThreadPool Executor. This way of processing makes the students more clear about the running rules of the thread pool and avoids the risk of resource exhaustion.
    Description
    1) FixedThreadPool
    uses LinkedBlockingQueue internally, which is allowed by default The length of the request queue is Integer. MAX_VALUE, which may accumulate a large number of task requests, resulting in OOM

    2)CachedThreadPool

    The allowed request queue length is Integer. MAX VALUE, which may create a large number of threads, resulting in OOM

ThreadPoolExecutor executor=new ThreadPoolExecutor(6,30,0L, TimeUnit.MINUTES,new LinkedBlockingDeque<>());
              
      
              for (int i = 0; i < 10; i++) {
      
                  executor.execute(new ThreadDemo());
              }
              executor.shutdown();

The thread pool is detailed in the thread pool series notes

  • java8 serial computing
   list.parallelStream().forEach(System.out::print);
  • @Async asynchronous method in Spring
Published 75 original articles · won praise 13 · views 8369

Guess you like

Origin blog.csdn.net/weixin_43696529/article/details/105210727