多线程概念与编程

一、多线程的生命周期:新建(New)、就绪(Runnable)、运行(Running)、阻塞(Blocked)和死亡(Dead)

1、新建状态:程序初始化一个Thread时,线程处于新建状态

2、就绪状态:线程Thread调用start()方法时,线程进入绪队列,等待调度运行

3、运行状态:线程获取CPU,运行run()或call()

4、堵塞状态:线程失去CPU,被挂起

5、死亡状态:线程正常运行结束或者异常退出,则线程消亡了

     

注意:suspend()resume()stop()这三个方法为废用方法,不推荐使用

 

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

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结束”

 

posted @ 2018-01-16 17:03  开着坦克的瑞兽  阅读(113)  评论(0编辑  收藏  举报