zoukankan      html  css  js  c++  java
  • java创建线程的几种方式

    1.继承Thread类

    /**
     * @author Ash
     * @date: 2016年8月6日 下午10:56:45 
     * @func: 通过继承Thread类来实现多线程
     * @email 408657544@qq.com
     * @Copyright: 2016 Ash. All rights reserved.
     */
    public class ExtendsThread extends Thread{
        public static void main(String[] args) {
            new ExtendsThread().start();
        }
        public void run() {
            System.out.println("hello");
        }
    }

    2.实现Runnable接口

    package com.test.thread;
    
    public class ImplementsRunable {
        public static void main(String[] args) {
            new Thread(new Task()).start();
        }
    }
    class Task implements Runnable {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            System.out.println("hello");
        }
    }

    3.使用线程池

    public class CallableFutureSample {
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            ExecutorService pool = Executors.newCachedThreadPool();
            for (int i = 0; i < 3; i++) {
                System.out.println(pool.submit(new Task3(i+"")).get());
            }
            pool.shutdown();
        }
    }
    
    class Task3 implements Callable<String> {
    
        private String taskname;
        public Task3(String taskname) {
            this.taskname=taskname;
        }
        @Override
        public String call() throws Exception {
            return taskname+" started";
        }
    }
  • 相关阅读:
    truncate删除一个分区,测试全局索引是否失效
    DG环境恢复同步遇到报错ORA-00353ORA-00334以及ORA-00600[2619], [47745]
    继承
    智能指针unique_ptr
    explicit
    编译安装python3
    Linux读写执行权限(-r、-w、-x)的真正含义
    nginx入门之编译安装
    vim
    1.yum下载 mysql及授权
  • 原文地址:https://www.cnblogs.com/heben/p/5745264.html
Copyright © 2011-2022 走看看