zoukankan      html  css  js  c++  java
  • Java线程使用备忘录

    前置概念

    并行与并发

    并行: 指多个事件在同一时刻发生

    并发: 指多个事件在同一时刻交替间隔发生

    进程与线程

    进程: 程序及运行资源的基本单位

    线程: 线程是进程中的一个实体, 是CPU调度与分配的基本单位

    使用线程的方式与方法

    继承Thread类, 调用线程的Start方法

    class A extends Thread{
            @Override
            public void run() {
                System.out.println("我是线程体.");
            }
        }
    
        public static void main(String[] args){
            A a = new A();
            a.start();
        }

    使用B类实现Runnable接口, 并使用Thread包装B, 调用线程的Start方法

    class B implements Runnable{
            @Override
            public void run() {
                System.out.println("我是B线程体.");
            }
        }
    
        public static void main(String[] args){
            Thread t = new Thread(new B());
            t.start();
        }

    使用C类实现Callable接口, 并使用FutureTask包装C产生D类, 并使用Thread包装D, 调用线程的Start方法 

    class C implements Callable{
            @Override
            public Object call() throws Exception {
                System.out.println("我是C线程体.");
                return 1;
            }
        }
    
        public static void main(String[] args){
            FutureTask ft = new FutureTask(new C());
            Thread t = new Thread(ft);
            t.start();
        }

    PS: C.call()方法的返回值, 使用ft.get()方法可以获取到

    使用总结

    继承Thread的类, 实例化后, 直接调取Start即可

    区别于实现Runnable的类, 实例化后, 需要通过Thread包装后, 再调取start

    以上两种实现方式, 不支持获取返回值

    如需要返回值, 需要使用Thread包装FutureTask类, 并自行实现Callable接口才行

  • 相关阅读:
    洛谷—— P2234 [HNOI2002]营业额统计
    BZOJ——3555: [Ctsc2014]企鹅QQ
    CodeVs——T 4919 线段树练习4
    python(35)- 异常处理
    August 29th 2016 Week 36th Monday
    August 28th 2016 Week 36th Sunday
    August 27th 2016 Week 35th Saturday
    August 26th 2016 Week 35th Friday
    August 25th 2016 Week 35th Thursday
    August 24th 2016 Week 35th Wednesday
  • 原文地址:https://www.cnblogs.com/wslio/p/14924831.html
Copyright © 2011-2022 走看看