JAVA之线程实现方式Test代码练习

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37722734/article/details/82454367

线程实现方式有四种,大型项目基本使用线程池,简要罗列代码块。

1、继承Thread类创建线程

/**
 * @author yto_yh
 *
 */
public class TestThread090601 extends Thread{
    
    /* (non-Javadoc)
     * @see java.lang.Thread#run()
     */
    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        System.out.println("线程启动");
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TestThread090601 t=new TestThread090601();
        TestThread090601 t1=new TestThread090601();
        t.start();
        t1.start();
    }

}

2.实现Runnable接口创建线程


/**
 * @author yto_yh
 *
 */
public class TestThread90602 implements Runnable{
    public void run() {
        System.out.println("线程启动");
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TestThread90602 tt=new TestThread90602();
        Thread t=new Thread(tt);
        t.start();
        Thread t1=new Thread(tt);
        t1.start();
    }

}

3、使用ExecutorService、Callable、Future实现有返回结果的线程

/**
 * @author yto_yh
 *
 */
public class TestCallable0903 implements Callable<Object>{
    

    private int threadNum;
    TestCallable0903(Integer threadNum){
        this.threadNum=threadNum;
    }
    /* (non-Javadoc)
     * @see java.util.concurrent.Callable#call()
     */
    @Override
    public Object call() throws Exception {
        System.out.println("第"+threadNum+"个线程启动!");
        return "第"+threadNum+"个线程结束!";
    }
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        int taskSize = 5;  
        ExecutorService pool = Executors.newFixedThreadPool(taskSize);  
        List<Future> list = new ArrayList<Future>();  
        for (int i = 0; i < taskSize; i++) {  
             Callable c = new TestCallable0903(i);  
             Future f = pool.submit(c);  
             list.add(f);  
        }  
        pool.shutdown();  
        for (Future f : list) {  
            System.out.println(">>>" + f.get().toString());  
        }  
    }
}

/**
 * @author yto_yh
 *
 */
public class TestCallable90302 {

    /**
     * @param args
     * @throws ExecutionException 
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException, ExecutionException {
      int threadNum=3;//创建线程数量
      List<Future> list =new ArrayList<Future>();
      ExecutorService executorService=Executors.newFixedThreadPool(threadNum);//创建线程池
      for(int i=0;i<threadNum;i++) {
         //提交有返回类型的任务
         Future f= executorService.submit((Callable)(new MyCallable(i+" ")));
         list.add(f);
      }
     executorService.shutdown(); 
    //遍历返回值
     list.forEach(s->{
        try {
            System.out.println(s.get().toString());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
      });
    }
}




/**
 * @author yto_yh
 *
 */
public class MyCallable implements Callable<Object>{
    
    private String taskNum;  
    
    MyCallable(String taskNum) {  
       this.taskNum = taskNum;  
    } 
    @Override
    public Object call() throws Exception {
        // TODO Auto-generated method stub
        System.out.println(">>>" + taskNum + "任务启动");  
        Date dateTmp1 = new Date();  
        Thread.sleep(1000);  
        Date dateTmp2 = new Date();  
        long time = dateTmp2.getTime() - dateTmp1.getTime();  
        System.out.println(">>>" + taskNum + "任务终止");  
        return taskNum + "任务返回运行结果,当前任务时间【" + time + "毫秒】";  
    }
  //实现call()方法,作为线程执行体
/*    public Integer call(){
        int i = 5;
        for( ; i<100 ; i++){
            System.out.println(Thread.currentThread().getName() + "的循环变量i的值:" +i);
        }
        //call()方法可以有返回值
        return i;
    }
    
    public static void main(String[] args) {
      //创建Callable对象
        Callable cd = new MyCallable();
        //使用FutureTask来包装Callable对象
        FutureTask<Integer> task = new FutureTask<Integer>(cd);
        for(int i=0 ; i<100 ; i++){
            System.out.println(Thread.currentThread().getName() + "的循环变量i的值:" +i);
            if(i==20){
                //实质还是以Callable对象来创建并启动线程
                new Thread(task,"有返回值的线程").start();
            }
        }
        try{
            System.out.println("子线程的返回值" + task.get());
            
        }catch(Exception e){
            e.printStackTrace();
        }
*/
    }

猜你喜欢

转载自blog.csdn.net/qq_37722734/article/details/82454367