Java基础 多线程的实现方式——实现 Runnable 接口的方式进行实现

发布时间 2023-10-27 15:49:57作者: 嘎嘎鸭2

实现 Runnable 接口的方式进行实现:

1. 定义一个类 实现 Runnable 接口,并实现 run 方法

2. 在 run 方法里面书写该线程要执行的代码

3. 然后创建这个 实现 Runnable 接口的类的实例化对象,这个对象其实就表示 多线程要执行的任务

4. 再去创建一个 Thread 类的对象,然后把  实现 Runnable 接口的那个类的对象 作为一个参数 传递进来

5. 开启线程

 

代码示例:

package pojo;

public class MyRun implements Runnable{
@Override
public void run() {
//getName() 是在 Thread 类里面的。我们的MyRun没有继承Thread

for (int i = 0; i < 3; i++) {
//先获取到当前线程的对象:Thread类当中的一个静态方法currentThread()
//currentThread()方法的返回值:表示当前是哪条线程执行到这个方法,那么这个方法就返回谁的对象
Thread t = Thread.currentThread();
System.out.println(t.getName() + "加油!");
}
/*
Test13_ThreadDemo 里,我们是创建了两个线程 t1和t2,这两个线程要执行的任务都是 mr,说白了就是 MyRun 里面的 run() 方法,
所以当程序启动之后,t1跟t2 都会执行 run() 方法里面的代码,那么在 run() 方法的循环当中,当 t1 执行到 Thread.currentThread() 时,
这个静态方法返回的就是 t1 的对象。同理,当 t2 执行到这个静态方法的时候,该静态方法返回的就是 t2 的对象
*/
}
}
--------------------------------------------------------------------------------
package test;

import pojo.MyRun;
import pojo.MyThread;

public class Test13_ThreadDemo {
public static void main(String[] args) {
//创建MyRun的对象,表示多线程要执行的任务
MyRun mr = new MyRun();

//创建两个线程对象
Thread t1 = new Thread(mr);
Thread t2 = new Thread(mr);

//给线程设置名字
t1.setName("线程一");
t2.setName("线程二");

//开启这两个线程
t1.start();
t2.start();
}
}