- Java code
-
class MyTheard extends Thread{ private int num = 5 ; // 不能声明为静态的全局变量 public void run(){ for ( int i = 0 ;i < 100 ;i ++ ){ if (num > 0 ){ System.out.println(Thread.currentThread().getName() + " 卖票 " + " : " + (num -- )); } } } } public class TheardDemo01 { public static void main(String[] args) { MyTheard th1 = new MyTheard(); MyTheard th2 = new MyTheard(); MyTheard th3 = new MyTheard(); th1.start(); th2.start(); th3.start(); } }
输出结果:
Thread-0卖票:5
Thread-0卖票:4
Thread-0卖票:3
Thread-0卖票:2
Thread-0卖票:1
Thread-2卖票:5
Thread-2卖票:4
Thread-2卖票:3
Thread-2卖票:2
Thread-2卖票:1
Thread-1卖票:5
Thread-1卖票:4
Thread-1卖票:3
Thread-1卖票:2
Thread-1卖票:1
- Java code
-
class MyThread implements Runnable { private int num = 5 ; public void run(){ for ( int i = 0 ;i < 100 ;i ++ ){ if (num > 0 ){ System.out.println(Thread.currentThread().getName() + " 卖票: " + " " + (num -- )); } } } }; public class ThreadDemo02 { public static void main(String[] args) { MyThread mt = new MyThread(); new Thread(mt).start(); new Thread(mt).start(); new Thread(mt).start(); } }
输出结果:
Thread-1卖票: 5
Thread-1卖票: 2
Thread-1卖票: 1
Thread-0卖票: 4
Thread-2卖票: 3
总结:
通过Rannable接口实现接口有如下的好处:
(1)适合于多个相同的程序代码的线程去处理同一资源。
(2)可以避免由于单继承带来的局限。
(3)增强了程序的健壮性,代码能够被多个线程共享,代码和数据独立。