1. 实现Runnable接口 implements Runnable
2. 重写run()方法
@Override
public void run(){//TODO}3. 创建线程对象:Thread thread1 = new Thread(new ImplementsRunnable());
4. 开启线程执行:thread1.start();
public class ImplementsRunnable implements Runnable{
public static int num = 0;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ": num = " + num++);
}
}
public static void main(String[] args) {
Thread thread1 = new Thread(new ImplementsRunnable());
Thread thread2 = new Thread(new ImplementsRunnable());
thread1.setName("线程1");
thread2.setName("线程2");
thread1.start();
thread2.start();
}
}
本文通过一个具体的Java代码示例,介绍了如何通过实现Runnable接口来创建和启动多线程。示例中展示了如何重写run()方法以定义线程的行为,并通过Thread类实例化线程并启动它们。
2987

被折叠的 条评论
为什么被折叠?



