Multi-threaded realization method [three]

Implement three implement the Callable interface

  • To implement the Callable interface, the return value type is required
  • Rewrite call method, need to throw an exception
  • Create a target audience
  • Create an execution service: ExecutorService ser=Executors.newFixedThreadPool(1);
  • Submit for execution: Future result1=ser.submit(t1);
  • Get the result: boolean r1=result1.get()
  • Shut down the service: ser.shutdownNow();

Case:

package Thread;

import java.util.concurrent.*;

public class TestCallable implements Callable<Boolean> {
    
    


        public Boolean call(){
    
    
            //call方法线程体
            for (int i = 0; i < 200; i++) {
    
    
                System.out.println("我在学习Java的多线程------"+i);
            }
            return  true;
        }


        public static void main(String[] args) throws ExecutionException, InterruptedException {
    
    
            //main线程, 主线程

            TestCallable t1 = new TestCallable();
            //创建执行服务
            ExecutorService ser= Executors.newFixedThreadPool(1);
            //提交执行
            Future<Boolean> r1=ser.submit(t1);
            //获取结果:
            boolean rs1=r1.get();
            //关闭服务
            ser.shutdownNow();

            for (int i = 0; i < 1000; i++) {
    
    
                System.out.println("我在学习JS的方法-------"+i);
            }

        }
    }

Guess you like

Origin blog.csdn.net/qq_45162683/article/details/111563716