码迷,mamicode.com
首页 > 编程语言 > 详细

多线程概念与编程

时间:2018-01-17 00:57:12      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:body   executor   return   override   ali   cut   service   多线程概念   adp   

一、多线程的三种实现方法

1、继承Thread类

public class MyThread extends Thread {
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println("我是Thread");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        System.out.println("结束main");
    }

}

2、实现Runnable接口

public class MyRunnable implements Runnable {

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println("我是runnable");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        new Thread(myRunnable).start();
        System.out.println("结束main");
    }

}

3、实现Callable接口

public class MyCallable implements Callable<Object> {

    @Override
    public Object call() throws Exception {
        Thread.sleep(1000);
        System.out.println("我是Callabel");
        return "我是Callabel";
    }
    
    public static void main(String[] args) throws Exception {
        ExecutorService  pool = Executors.newCachedThreadPool();
        MyCallable myCallable = new MyCallable();
        pool.submit(myCallable);    
//        Future<Object> f = pool.submit(myCallable);
//        System.out.println(f.get().toString());    
        System.out.println("main结束");
    }
}

注:当用Future去接收call()返回值,该方法是阻塞的,即先打印“我是Callable”再打印“main结束”

 

多线程概念与编程

标签:body   executor   return   override   ali   cut   service   多线程概念   adp   

原文地址:https://www.cnblogs.com/chensr/p/8297576.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!