java笔记线程方式2

方式2:实现Runnable接口
 * 步骤:
 *   A:自定义类MyRunnable实现Runnable接口
 *   B:重写run()方法
 *   C:创建MyRunnable类的对象
 *   D:创建Thread类的对象,并把C步骤的对象作为构造参数传递

 1 public class MyRunnableDemo {
 2     public static void main(String[] args) {
 3         // 创建MyRunnable类的对象
 4         MyRunnable my = new MyRunnable();
 5 
 6         // 创建Thread类的对象,并把C步骤的对象作为构造参数传递
 7         // Thread(Runnable target)
 8         // Thread t1 = new Thread(my);
 9         // Thread t2 = new Thread(my);
10         // t1.setName("林青霞");
11         // t2.setName("刘意");
12 
13         // Thread(Runnable target, String name)
14         Thread t1 = new Thread(my, "林青霞");
15         Thread t2 = new Thread(my, "刘意");
16 
17         t1.start();
18         t2.start();
19     }
20 }
21 public class MyRunnable implements Runnable {
22 
23     @Override
24     public void run() {
25         for (int x = 0; x < 100; x++) {
26             // 由于实现接口的方式就不能直接使用Thread类的方法了,但是可以间接的使用
27             System.out.println(Thread.currentThread().getName() + ":" + x);
28         }
29     }
30 
31 }
原文地址:https://www.cnblogs.com/lanjianhappy/p/6383975.html