多线程的实现方式

1. 继承Thread类,重写run方法,调用start

class MyThread extends Thread {
	@Override
	public void run() {
		//此处为thread执行的任务内容
		System.out.println(Thread.currentThread().getName());
	}
}

public static void main(String[] args) {
	for(int i=0;i<2;i++) {
		Thread t = new Thread(new MyThread());
		t.start();
	}
}

2. 实现Runnable接口,用新的类创建Thread实例,调用start

class MyThread implements Runnable {
	@Override
	public void run() {
		//此处为thread执行的任务内容
		System.out.println(Thread.currentThread().getName());
	}
}

public static void main(String[] args) {
	for(int i=0;i<2;i++) {
		Thread t = new Thread(new MyThread());
		t.start();
	}
}

3. 实现Callable接口,用新的类创建Thread实例,调用start

class MyThread extends Callable<String> {
	@Override
	public String call() {
		//此处为thread执行的任务内容
		System.out.println(Thread.currentThread().getName());
		return "执行线程";
	}
}

public static void main(String[] args) {
	for(int i=0;i<2;i++) {
		//创建MyThread实例
		Callable<Integer> c = new MyThread();
		//获取FutureTask
		FutureTask<Integer> ft = new FutureTask<Integer>(c);
		//使用FutureTask初始化Thread
		Thread t = new Thread(ft);
		t.start();
		// 获取结果
		String result =ft.get();
	}
}

4. 线程池

class MyThread implements Runnable {
	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName());
	}
	
}

class MyThread2 implements Callable<String> {
	@Override
	public String call() throws Exception {
		System.out.println(Thread.currentThread().getName());
		return null;
	}

	
}

public static void main(String[] args) {
	// 固定数量的线程池
	ExecutorService executorService = Executors.newFixedThreadPool(5);
	for(int i=0;i<2;i++) {
		executorService.execute(new MyThread());
		FutureTask<Integer> ft = new FutureTask<Integer>(new MyThread2());
		executorService.submit(ft);
	}
	executorService.shutdown();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值