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

    一,继承Thread类,实现run()方法:

    以下示例可以看见,继承Thread类再重写run()方法,便可创建一个线程。start()方法启动一个线程。
     1 public class Test_1 extends Thread {  
     2     public static void main(String[] args) throws InterruptedException {
     3         Test_1 t1=new Test_1();
     4         Test_1 t2=new Test_1();
     5         t1.start();//启动线程
     6         t2.start();
     7     }
     8     public void run(){
     9         for (int i = 1; i <= 10; i++) {  //每个线程都会执行这个循环
    10             System.out.println(Thread.currentThread().getName()+"_"+i);
    11         }
    12     }
    13 }

    二.实现Runnable接口,重写run()方法。

    public class Test_Runnable implements Runnable {
        public static void main(String[] args) {
            Test_Runnable t=new Test_Runnable();
            Thread t1=new Thread(t,"Thread_1");//采用构造方法:Thread(Runnable target,String name)
            Thread t2=new Thread(t,"Thread_2");
            Thread t3=new Thread(t,"Thread_3");
            t1.start();  //启动线程
            t2.start();
            t3.start();
        }
    
        @Override
        public void run() {  //重写的run()方法
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName()+"_"+i);
            }
        }
    }

    三,实现Callable接口

    public class Test_2_Callable implements Callable<Integer> {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            Test_2_Callable t=new Test_2_Callable();
            //FutureTask类,接收返回结果
            FutureTask<Integer> res=new FutureTask<>(t);
            //启动线程,FutureTask实现了Runnable接口
            new Thread(res).start();
            //接收返回结果
            int i=res.get();
            System.out.println(i);
        }
    
        @Override
        public Integer call() throws Exception {
            //继承Callable接口,重写call()方法,该方法返回<V>或者抛出异常
            int sum=0;
            for (int i = 1; i <=100; i++) {
                sum+=i;
            }
            return sum;
        }
    }

    总结:在继承Thread类,和实现Runnable接口中推荐使用实现Runnable接口。因为在Java中类只能单继承,所以采用实现Runnable接口更加灵活方便。而第三种方式:实现Callable接口(只含有唯一的方法:call()),重写call()方法,该方法有返回值<V>,或者抛出异常。可以采用FutureTask类中的get()方法接收返回值。

    Thread(Runnable target, String name)

    分配一个新的 Thread对象。
  • 相关阅读:
    【POJ 3669】Meteor Shower
    【BZOJ 1003】[ZJOI2006]物流运输trans
    【POJ 3662】Telephone Lines
    【UVa 1593】Alignment of Code
    【POJ 3661】Running
    [HNOI2015]开店 简要题解
    trie上构建后缀数组
    [CQOI2017]老C的方块
    [JSOI2018]潜入行动 (树形背包)
    李超线段树 总结
  • 原文地址:https://www.cnblogs.com/xbfchder/p/10961492.html
Copyright © 2011-2022 走看看