Java多线程的4种实现方式

**

Java多线程的4种实现方式

**

1:继承Thread并重写run方法,并调用start方法

/**
 * Java实现多线程的方式1
 * 继承Thread类,重写run方法
 * @author hongbo.zhao 2019年4月12日 上午7:12:35
 */
class MyThread extends Thread {
	
	@Override
	public void run() {
		//此处为thread执行的任务内容
		System.out.println(Thread.currentThread().getName());
	}
}

public class Demo03 {
	
	
	public static void main(String[] args) {
		
		for(int i=0;i<2;i++) {
			Thread t = new MyThread();
			//输出:
			//Thread-0 Thread-1
			t.start();
		}
	}
}

2:实现Runnable接口,并用其初始化Thread,然后创建Thread实例,并调用start方法

/**
 * Java实现多线程的方式2
 * 实现Runnable接口
 * @author hongbo.zhao 2019年4月12日 上午7:12:35
 */
class MyThread implements Runnable {
	
	@Override
	public void run() {
		//此处为thread执行的任务内容
		System.out.println(Thread.currentThread().getName());
	}
}

public class Demo03 {
	
	
	public static void main(String[] args) {
		
		for(int i=0;i<2;i++) {
			Thread t = new Thread(new MyThread());
			//输出:
			//Thread-0 Thread-1
			t.start();
		}
	}
}

3:实现Callable接口,并用其初始化Thread,然后创建Thread实例,并调用start方法


/**
 * Java实现多线程的方式3
 * 实现Callable接口
 * @author hongbo.zhao 2019年4月12日 上午7:12:35
 */
class MyThread implements Callable<Integer> {
	
	@Override
	public Integer call() throws Exception {
		System.out.println(Thread.currentThread().getName());
		return null;
	}
}

public class Demo03 {
	
	
	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);
			//输出:
			//Thread-0 Thread-1
			t.start();
		}
	}
}

4:使用线程池创建


/**
 * Java实现多线程的方式4
 * 线程池
 * @author hongbo.zhao 2019年4月12日 上午7:12:35
 */
class MyThread implements Runnable {

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

class MyThread2 implements Callable<Integer> {

	@Override
	public Integer call() throws Exception {
		System.out.println(Thread.currentThread().getName());
		return 0;
	}

	
}

public class Demo03 {
	
	
	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());
			//输出
//			pool-1-thread-1
//			pool-1-thread-2
//			pool-1-thread-3
//			pool-1-thread-4
			executorService.submit(ft);
		}
		executorService.shutdown();
	}
}
  • 9
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值