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 接口

  • 相关阅读:
    BISDN上收集到的SAP BI的极好文章的链接
    如何设置'REUSE_ALV_GRID_DISPLAY'的单个单元格的颜色
    如何设置REUSE_ALV_GRID_DISPLAY'的单个单元格的是否可以输入
    BWABAP to copy aggregates from one cube to another
    SDva01的屏幕增强
    js鼠标悬停效果
    MySQL更新UPDATA的使用
    使用mysql C语言API编写程序—MYSQL数据库查询操作
    MySQL的部分基础语句
    MySQLdelete某个元组||、&&操作
  • 原文地址:https://www.cnblogs.com/yufeng218/p/9940909.html
Copyright © 2011-2022 走看看