创建线程的四种方式、超详细,有示例代码

创建线程的四种方式分别是:继承Thread类、实现Runnable接口、通过ExecutorService和Callable<Class>实现有返回值的线程、基于线程池

1.实现Runnable接口

OneThread类

public class OneThread implements Runnable {

    @Override
    public void run() {
        System.out.println("6666666666666666666666666666666666");
    }
}

Test类

void test26() throws ExecutionException, InterruptedException {

OneThread oneThread = new OneThread();
	Thread thread = new Thread(oneThread);
	thread.start();


}

控制台输出

6666666666666666666666666666666666

 

2.继承Thread类

TwoThread类

public class TwoThread extends Thread {
    @Override
    public void run() {
        System.out.println("777777777777777777777777777777");
    }
}

 Test类

	void test26() throws ExecutionException, InterruptedException {

	TwoThread twoThread = new TwoThread();
	twoThread.start();

    }

控制台输出

777777777777777777777777777777

 

3.通过ExecutorServie和Callable<Class>实现有返回值的线程

 ThreeThread类

public class ThreeThread implements Callable<String> {
    private String name;

    public ThreeThread(String name) {
        this.name = name;
    }

    @Override
    public String call() throws Exception {
        return name;
    }
}

Test类

ExecutorService executorService = Executors.newFixedThreadPool(5);
		List<Future> list = new ArrayList<Future>();
		for (int i =0; i< 5; i++){
			Callable c = new ThreeThread(i+"");
			Future future = executorService.submit(c);
			System.out.println("submit a callable thread:"+i);
			list.add(future);
		}
		executorService.shutdown();
		for (Future future : list){
			System.out.println("get the result from callable thread:"+ future.get().toString());
		}

 控制台输出

submit a callable thread:0
submit a callable thread:1
submit a callable thread:2
submit a callable thread:3
submit a callable thread:4
get the result from callable thread:0
get the result from callable thread:1
get the result from callable thread:2
get the result from callable thread:3
get the result from callable thread:4

4.基于线程池

Test类

ExecutorService threadPool = Executors.newFixedThreadPool(10);
	for (int i =0; i<10;i++){
	threadPool.execute(new Runnable() {
		@Override
		public void run() {
			System.out.println(Thread.currentThread().getName()+"is running");
		}
	});
	}

控制台输出

pool-1-thread-1is running
pool-1-thread-4is running
pool-1-thread-3is running
pool-1-thread-2is running
pool-1-thread-5is running
pool-1-thread-6is running
pool-1-thread-7is running
pool-1-thread-8is running
pool-1-thread-9is running
pool-1-thread-10is running

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值