java多线程

目录

实现多线程的三种方式:

1、继承thread类

2、实现Runable接口

3、实现Callable和Future接口(优点是可以获取多线程的结果)


1、继承thread类

package com.jyt.thread;
/*
多线程启动的第一种方式:
1、自己定义一个类继承Thread
2、重写run方法
3、创建子类对象开启线程
 */
public class MyThread extends Thread{
    @Override
    //重写run方法,求1-100的和
    public void run() {
        int sum=0;
        for (int i = 0; i <= 100; i++) {
            sum+=i;
        }
        System.out.println(sum);
    }

    public static void main(String[] args) {
        //实例化两个类对象,起名,开启线程
        MyThread mt1=new MyThread();
        MyThread mt2=new MyThread();
        mt1.setName("线程1");
        mt2.setName("线程2");
        mt1.start();
        mt2.start();

    }
}

运行结果:

2、实现Runable接口

package com.jyt.thread;
/*
多线程的第二种实现方式:
1、自己定义一个类实现runable接口,
2、重写run方法
3、创建自己的类对象
4、创建thread对象,开启线程
 */
public class runable implements Runnable{
    @Override
    public void run() {
        //线程1、2交替进行,分别输出10次hello
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+"hello"+i);
        }
    }
    public static void main(String[] args) {
        runable rb=new runable();//实例化runable的对象,相当于任务类
        Thread th1=new Thread(rb);//将runable对象作为Thread的参数
        Thread th2=new Thread(rb);
        th1.setName("线程1");
        th2.setName("线程2");
        th1.start();
        th2.start();
    }
}

结果:

3、实现Callable和Future接口(优点是可以获取多线程的结果)

package com.jyt.thread;
/*
多线程的第三种实现方式:
1、创建类实现Callable接口,并重写call方法
2、实例化创建的类对象,即任务类
3、创建FutureTask对象,用于管理结果
4、创建thread对象,并start
 */
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class caller implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int sum=0;
        for (int i = 0; i <= 10; i++) {
            sum+=i;
        }
        return sum;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
       caller ca= new caller();
        FutureTask<Integer> ft=new FutureTask<>(ca);
        Thread th=new Thread(ft);
        th.start();
        //显示结果
        System.out.println(ft.get());

    }
}

运行结果:

 

  • 17
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值