Java 多线程编程:使用 Runnable 接口实现多线程
以下是一个实现 Runnable 接口的多线程的代码示例:
public class MyRunnable implements Runnable {
@Override
public void run() {
// 在这里编写多线程任务代码
System.out.println('当前线程名称:' + Thread.currentThread().getName());
}
public static void main(String[] args) {
// 创建线程并启动
Thread thread1 = new Thread(new MyRunnable());
Thread thread2 = new Thread(new MyRunnable());
thread1.start();
thread2.start();
}
}
在这个代码中,我们首先创建了一个实现了 Runnable 接口的类 MyRunnable,然后在类中实现了 run() 方法,并在 run() 方法中编写了多线程任务代码。在 main() 方法中,我们创建了两个线程对象 thread1 和 thread2,并将 MyRunnable 实例作为参数传递给它们。最后,我们调用 start() 方法启动这两个线程,实现了多线程执行任务的效果。
原文地址: https://www.cveoy.top/t/topic/ogi2 著作权归作者所有。请勿转载和采集!