实现多线程的几种方式

实现多线程的几种方式

1、通过继承Thread类


public class test1 extends Thread{
	private String name;
	public test1(String name) {
		 this.name=name;
	}
	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println(this.name+"正在执行"+i);
		}
	}
	public static void main(String[] args) {
		new test1("A").start();
		new test1("B").start();
		new test1("C").start();
	}
	
}

优点:轻松实现,实例化对象之后,直接调用start方法即可。
缺点:Java单继承局限,所以一般不用

2、实现Runnable接口

public class test2 implements Runnable{
	private String name;
	public test2(String name) {
		 this.name = name;
	}
	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println(this.name+"正在执行"+i);
		}
	}
	public static void main(String[] args) {
		test2 testA = new test2("A");
		test2 testB = new test2("B");
		test2 testC = new test2("C");
		new Thread(testA).start();
		new Thread(testB).start();
		new Thread(testC).start();
	}
}

优点:避免了单继承局限
缺点:实现有点繁琐

使用Lambda表达式简化实现Runnable接口


public class test3 {
	
	public static void main(String[] args) {
			new Thread(()->{
				for (int i = 0; i < 10; i++) {
					System.out.println("a正在执行"+i);
				}	
			}).start();
			
			new Thread(()->{
				for (int i = 0; i < 10; i++) {
					System.out.println("b正在执行"+i);
				}	
			}).start();
			new Thread(()->{
				for (int i = 0; i < 10; i++) {
					System.out.println("c正在执行"+i);
				}	
			}).start();
	}
	
}

优点:简化操作,代码更简洁
缺点:lambda表达式现在还不会使

实现Callable接口,实现多线程

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

public class test4 implements Callable<String>{
	String str = "";
	@Override
	public String call() throws Exception {
		for (int i = 0; i < 5; i++) {
			this.str+="hello world\n";
		}	
		return str;
	}
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		test4 test4 = new test4();
		FutureTask<String> futureTask = new FutureTask<String>(test4);
		Thread thread = new Thread(futureTask);
		thread.start();
		String h = futureTask.get();
		System.out.println(h); 
	}
}

优点:避免了单继承局限,可以有返回值
缺点:实现有点繁琐

最后总结:实现多线程一般使用Callable接口或者Runnable接口,
如果有返回值就用Callable接口,无返回值就用Runnable接口。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值