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对象。
  • 相关阅读:
    Android 自定义title样式
    HDU 3094 A tree game 树删边游戏
    设计模式学习笔记观察者模式
    [Unity-7] Update和FixedUpdate
    一淘搜索网页抓取系统的分析与实现(3)—scrapy+webkit &amp; mysql+django
    POJ 1947 树DP获得冠军
    linux 下一个 jira-6.3.6 组态 皴 翻译 迁移数据库
    阐述linux IPC(五岁以下儿童):system V共享内存
    使用OpenCV玩家营造出一个视频控制(没有声音)
    Swift编程语言学习4.1——周期
  • 原文地址:https://www.cnblogs.com/xbfchder/p/10961492.html
Copyright © 2011-2022 走看看