五、实现Runnable接口
步骤:
- 定义MyRunnable类实现Runnable接口
- 实现run()方法,编写线程执行体
- 创建线程对象(将MyRunnable实例作为线程对象创建时的参数),调用start()方法启动线程
代码:
public class MyRunnable implements Runnable{ @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println("我是子线程:"+i); } } public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); thread.start(); for (int i = 0; i < 200; i++) { System.out.println("我是主线程:"+i); } } }
结果: