线程 实现的两种方法

 1 package thread;
 2 
 3 public class MyRunnable implements Runnable {
 4 
 5     private int i = 1;
 6 
 7     @Override
 8     public void run() {
 9 
10         for (i = 1; i <= 100; i++) {
11             System.out.println(Thread.currentThread().getName() + " " + i);// 获取当前运行的线程名称
12         }
13 
14     }
15 
16 }
 1 package thread;
 2 
 3 public class MyThread extends Thread {
 4 
 5     private int i = 1;
 6 
 7     @Override
 8     public void run() {
 9 
10         for (i = 1; i <= 100; i++) {
11             System.out.println(Thread.currentThread().getName() + " " + i);// 获取当前运行的线程名称
12         }
13     }
14 
15 }
 1 package thread;
 2 
 3 public class Test {
 4 
 5     public static void main(String[] args) {
 6 
 7         Thread t1 = new MyThread();
 8         Thread t2 = new MyThread();// 创建线程
 9 
10         t1.start();
11         t2.start();// 就绪线程
12 
13         Runnable r = new MyRunnable();
14 
15         Thread t3 = new Thread(r);
16         Thread t4 = new Thread(r);// 创建线程
17 
18         t3.start();
19         t4.start();// 就绪线程
20 
21     }
22 
23 }

猜你喜欢

转载自www.cnblogs.com/ybxxszl/p/9314142.html