zoukankan      html  css  js  c++  java
  • 52、多线程创建的三种方式对比

    多线程创建的三种方式对比

    • 继承Thread
      • 优点:可以直接使用Thread类中的方法,代码简单
      • 缺点:继承Thread类之后就不能继承其他的类
    • 实现Runnable接口
      • 优点:即时自定义类已经有父类了也不受影响,因为可以实现多个接口
      • 缺点: 在run方法内部需要获取到当前线程的Thread对象后才能使用Thread中的方法
    • 实现Callable接口
      • 优点:可以获取返回值,可以抛出异常
      • 缺点:代码编写较为复杂

    使用匿名内部类创建线程

    package com.sutaoyu.Thread;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class test_4 {
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            /*
             * Thread
             */
            new Thread() { // 1.继承Thread类
                public void run() { // 2.重写run方法
                    for(int i = 0;i<1000;i++) { // 3.将要执行的代码写在run方法中
                        System.out.println(i + "Thread"); 
                    }
                }
            }.start(); // 4.开启线程
            
            /*
             * Runnable
             */
            
            new Thread(new Runnable() { // 1.将Runnable的子类对象传递给Thread的构造方法
                public void run() { // 2.重写run方法
                    for(int i = 0;i < 1000;i++) {
                        System.out.println( i + "Runnable");
                    }
                }
            }).start();// 4.开启线程
            
            /*
             * Callable
             */
            
            ExecutorService exec = Executors.newCachedThreadPool();
            Future<Integer> result = exec.submit(new Callable<Integer>() {
                
                public Integer call() throws Exception{
                    return 1024;
                }
            });
            System.out.println(result.get());
        }
    }
  • 相关阅读:
    2010年8月18日周三_Migrating from 1.3 to 2.0_5
    2010年8月12日_周四_UserControlTask control
    2010年8月18日周三_insideTheAPI_overView_6.1
    一个Flex事件的简单的例子
    2010年8月13日_周五_PrintTask control
    如何发布一个GeometryService服务
    lua分割字符串
    lua字符串合并
    lua 类型转换
    linux 下 svn 冲突解决办法
  • 原文地址:https://www.cnblogs.com/zhuifeng-mayi/p/10149658.html
Copyright © 2011-2022 走看看