创建多线程

创建多线程

继承Thread类,并重写run方法

public class MyThread extends Thread {
	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
		// getName: 获取线程的名称
			System.out.println(getName() + "  ---  " + i);
		}
	}
}

测试通过继承创建线程

public static void main(String[] args) throws Exception {
	MyThread t1 = new MyThread();
	MyThread t2 = new MyThread();
	MyThread t3 = new MyThread();
	// 通过start来启动线程
	t1.start();
	t2.start();
	t3.start();
	// 可以通过setName给线程添加名称
	t1.setName("线程1");
}

可以通过实现Runnable接口来创建多线程

public class MyRunnable implements Runnable{
	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
		  	// 可以通过Thread的currentThread()方法来获取当前线程
		  	//再通过当前线程来调用getName来获取线程名称
			System.out.println(Thread.currentThread().getName() + "  ---  " + i);
		}
	}
}

测试通过实现接口创建线程

main方法
```java
public static void main(String[] args) throws Exception {
	MyRunnable r1 = new MyRunnable();
	Thread t1 = new Thread(r1);
	Thread t2 = new Thread(r1);
	Thread t3 = new Thread(r1);
	t1.start();
	t2.start();
	t3.start();
}

Runnable接口是一个函数式接口,我们还可以通过lambda表达式来实现
在这里插入图片描述

public static void main(String[] args) throws Exception {
	new Thread(() -> {
		for (int i = 0; i < 100; i++) {
			System.out.println(Thread.currentThread().getName() + "  ---  " + i);
		}
	}).start();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值