多线程的三种实现方式

1.继承Thread类进行实现

//继承Thread类进行实现
public class threadcase1 {
    //定义一个类继承Thread
    public static class  MyThread extends Thread{
        public void run() {
            for (int i = 0; i < 100; i++) {
                System.out.println(getName() + "HelloWorld");
            }
        }
    }
    public static void main(String[] args){
        MyThread m1=new MyThread();
        MyThread m2=new MyThread();
        //给线程设置名字
        m1.setName("进程1");
        m2.setName("进程2");
        //启动线程
        m1.start();
        m2.start();
    }
}

 2.利用Runnable接口实现

//利用Runnable接口实现
public class threadcase2 {
    public static class run implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                //获取到当前线程的对象
                Thread t=Thread.currentThread();

                System.out.println(t.getName()+"HelloWorld");
            }
        }
    }
    public static void main(String[] args){
        run r=new run();
        //创建线程对象
        Thread t1=new Thread(r);
        Thread t2=new Thread(r);
        //给线程设置名字
        t1.setName("线程1");
        t2.setName("线程2");
        //启动线程
        t1.start();
        t2.start();
    }
}

可以从结果看到并不是执行完线程一之后再执行线程二

 想要获取多线程运行的结果, 可以用第三种方法

3.利用Callable接口和Future接口实现

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//利用Callable接口和Future接口实现
public class threadcase3 {
    public static class MyCallable implements Callable<Integer>{
        @Override
        public Integer call() throws Exception {
            int sum=0;
            for(int i=1;i<=100;i++){
                sum+=i;
            }
            return sum;
        }
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建MyCallable对象(表示多线程要执行的任务)
        MyCallable mc=new MyCallable();
        //创建FutureTask对象(管理多线程运行的结果)
        FutureTask<Integer>ft=new FutureTask<>(mc);
        //创建线程的对象
        Thread t=new Thread(ft);
        //启动线程
        t.start();
        //输出结果为1到100的和,即 5050
        System.out.println(ft.get());
    }
}

初学者,见解不足,如有错误请指出

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值