多线程创建方式

目录

1、继承Thread类,重写run方法

2、实现Runnable接口,重写run方法

3、使用匿名内部类方式

4、实现Callable接口,重写run方法


1、继承Thread类,重写run方法

class ThreadDemo extends Thread {
	@Override
	public void run() {
		//多线程需要执行的代码
	}
}
public class Test {
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			// 1.创建线程
			ThreadDemo threadDemo = new ThreadDemo();
			// 2.启动线程
			threadDemo.start();
		}
	}
}

2、实现Runnable接口,重写run方法

class RunnableDemo implements Runnable {
	@Override
	public void run() {
		//多线程需要执行的代码
	}
}
public class Test {
	public static void main(String[] args) {
		// 1.创建runable实现类
		RunnableDemo runnableDemo = new RunnableDemo();
		for (int i = 0; i < 10; i++) {
			// 2.创建线程
			Thread threadDemo = new Thread(runnableDemo);
			// 3.启动线程
			threadDemo.start();
		}
	}
}

3、使用匿名内部类方式

public class Test {
	public static void main(String[] args) {
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				多线程需要执行的代码
			}
		});
		t1.start();
	}
}

4、实现Callable接口,重写run方法

class CallableDemo implements Callable<String> {
	@Override
	public String call() throws Exception {
		//多线程需要执行的代码
		return "succeed";
	}
}
public class Test {
	public static void main(String[] args) throws ExecutionException, InterruptedException {
		// 1.创建callable实现类
		CallableDemo callableDemo = new CallableDemo();
		//创建一个FutureTask实现类
		FutureTask<String> futureTask = new FutureTask<String>(callableDemo);
		for (int i = 0; i < 10; i++) {
			// 2.创建线程
			Thread threadDemo = new Thread(futureTask);
			// 3.启动线程
			threadDemo.start();
			//获得返回值
			System.out.println(futureTask.get());
		}
	}
}

5、线程池

详见线程池篇

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值