使用实现 Runnable 接口的方式创建线程,在主线程中运行该线程,两个线程会随机交替运行。
定义一个线程类,该类实现 Runnable 接口,在线程中循环遍历 1 – 1000 所有数字。
定义 main 方法,启动该线程,然后再使用循环遍历 1–1000 所有数字。
MyRunnable 类:
public class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
String name = Thread.currentThread().getName();
System.out.println(name + ":i = " + i);
}
}
}
测试类:
public class Test {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)\n");
Thread mt = new Thread(new MyRunnable(),"MyThread");
mt.start();
for (int j = 0; j < 1000; j++) {
String name = Thread.currentThread().getName();
System.out.println(name + ":j = " + j);
}
}
}
运行结果如下图:
以上案例使用实现 Runnable 方法的方式定义线程类。