创建多线程_JAVA常用创建多线程的两种方法

多线程是Java学习中的一个很重要的知识点,对于多线程的五种状态运行机制等,开头不再多讲,因为,怕大家看了开始就头大,后面的内容就不想了解了。我们先从简单实用的开始:

35168e650970a0386d5f48c2c6c134c4.png

第一种方法继承Thread创建多线程:

Java中万物皆对象,多线程也不例外,脑海中第一个想法就是要创建一个类继承Thread父类。并且重写父类中的run方法。

直接上代码:

class MyThread extends Thread {

private int i = 0;

public void run() {

for (i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName() + " " + i); }

}

}

public class ThreadTest {

public static void main(String[] args) {

for (int i = 0; i < 100; i++) {

System.out.println(Thread.currentThread().getName() + " " + i);

if (i == 30) {

Thread myThread1 = new MyThread();

// 创建一个新的线程 myThread1 此线程进入新建状态

Thread myThread2 = new MyThread();

// 创建一个新的线程 myThread2 此线程进入新建状态

myThread1.start();

// 调用start()方法使得线程进入就绪状态

myThread2.start();

// 调用start()方法使得线程进入就绪状态

}

}

}

}

第二种方法:实现Runnable接口,并重写该接口的run()方法:

class MyRunnable implements Runnable {

private int i = 0;

public void run() {

for (i = 0; i < 100; i++) {

System.out.println(Thread.currentThread().getName() + " " + i);

}

}

} //实现Runnable接口

public class ThreadTest {

public static void main(String[] args) {

for (int i = 0; i < 100; i++) {

System.out.println(Thread.currentThread().getName() + " " + i);

if (i == 30) {

Runnable myRunnable = new MyRunnable();

// 创建一个Runnable实现类的对象

Thread thread1 = new Thread(myRunnable);

// 将myRunnable作为Thread target创建新的线程

Thread thread2 = new Thread(myRunnable);

thread1.start();

// 调用start()方法使得线程进入就绪状态

thread2.start();

}

}

}

}

df3caa01e6eaa58a934f07ec70c39dc8.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值