zoukankan      html  css  js  c++  java
  • 线程的三种实现方法

    线程的三种实现方法:
    (1)继承 Thread 类,重写run()方法;

    (2)实现 Runnable 接口,重写run() 方法;

    (3)实现 Callable 接口,重写call()方法;

    方式一:  继承Thread类

    public class MyThreadDemo
    {
        public static void main(String[] args)
        {
            Thread thread = new MyThread();
            thread.start();
        }
    }
    
    class MyThread extends Thread
    {
        @Override
        public void run()
        {
            System.out.println("extends Thread");
        }
    }

    方式二: 实现 Runnable 接口

    public class MyRunnableDemo
    {
        public static void main(String[] args)
        {
            //方法一
            Thread thread = new Thread(new MyRunnable());
            thread.start(); //启动线程
    
            //方法二 匿名类
            Thread thread1 = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    System.out.println("anonymous class implement Runnable");
                }
            });
            thread1.start(); //启动线程
        }
    }
    
    class MyRunnable implements Runnable
    {
    
        @Override
        public void run()
        {
            System.out.println("implement Runnable");
        }
    }

    方式三: 实现 Callable 接口

    Callable 的 call() 方法会返回执行结果,抛出异常;

    ExecutorService :线程池的接口;

    Executors: 线程池的工具类

    public class MyCallableDemo
    {
        public static void main(String[] args) throws ExecutionException, InterruptedException
        {
            //方法一  使用线程池方式
            ExecutorService executorService = Executors.newFixedThreadPool(2);
            Future future = executorService.submit(new MyCallable());
            future.isDone();      //return true,false 无阻塞
            System.out.println(future.get());    // return 返回值,阻塞直到该线程运行结束
    
            //方法二
            FutureTask futureTask = new FutureTask(new MyCallable());
            Thread thread = new Thread(futureTask);
            thread.start();
            System.out.println(futureTask.get());
        }
    }
    
    class MyCallable implements Callable
    {
        @Override
        public String call() throws Exception
        {
            System.out.println(Thread.currentThread().getName() + ": 执行 Call 方法");
            return Thread.currentThread().getName() + "线程运行完成";
        }
    }

    运行结果: 

      

    FutureTask 类实现了 Runnable 接口

  • 相关阅读:
    mybatis源码追踪2——将结果集映射为map
    Mybatis的cache
    mybatis拦截器
    mybatis中单个参数的引用
    mybatis源码追踪1——Mapper方法用法解析
    win8 下 intellij idea 13 中文输入覆盖的问题
    firebug中html显示为灰色的原因总结
    extjs4.0以上添加多行工具栏的方法
    去除eclipse的validating
    An interview question from MicroStrategy
  • 原文地址:https://www.cnblogs.com/yufeng218/p/9940909.html
Copyright © 2011-2022 走看看