创造线程的几种方式

一:继承Thread类,重写run方法

package CreateThread;
public class ExtendThread {
    public static void main(String[] args) {
        MyThreadOne threadOne=new MyThreadOne();
        threadOne.start();
        for (int i = 0; i < 100; i++) {
            System.out.println("main:" + i);
        }
    }
}
class MyThreadOne extends Thread{
    @Override
    public void run() {
        for (int i = 0; i <10000 ; i++) {
            System.out.println("myjob"+i);
        }
    }
}

这个方法不推荐,因为Java类是单继承的,这样会影响后续代码的扩展。

二:实现Runnable接口 重写run方法

package CreateThread;
public class ImplRunnable {
    public static void main(String[] args) {
        MyRunnable runnable =new MyRunnable();
        Thread thread=new Thread(runnable);
        thread.start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("main:" + i);
        }
    }
}
class MyRunnable implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("MyRunnable:" + i);
        }
    }
}

最常用的方式如下:
匿名内部类:

 Thread thread=new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < 1000; i++) {
                            System.out.println("匿名内部类:" + i);
                        }
                    }
                }
        );
        thread.start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("main:" + i);
        }

lambda方式:

Thread t2 = new Thread(() -> {
    for (int i = 0; i < 100; i++) {
        System.out.println("lambda:" + i);
    }
});

三:实现Callable 重写call方法,配合FutureTask

Callable一般用于有返回结果的非阻塞的执行方法

package CreateThread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class ImlCallable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable myCallable=new MyCallable();
        // 创建FutureTask
        FutureTask futureTask=new FutureTask(myCallable);
        Thread thread=new Thread(futureTask);
        thread.start();
        //5. 做一些操作
        //6. 要结果
        Object count = futureTask.get();
        System.out.println("总和为:" + count);
    }
}
class MyCallable implements Callable {


    @Override
    public Object call() throws Exception {
        int count = 0 ;
        for (int i = 0; i < 100; i++) {
            count = count+i;
        }
        return count ;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值