两个演员线程交替进行,一个直接继承Thread实现,另一个通过Runnable接口实现。
1 package cn.test.muke; 2 3 public class Actor extends Thread { 4 5 @Override 6 public void run() { 7 System.out.println(getName() + "是一个演员!"); 8 int count = 0; 9 boolean keepRunning = true; 10 11 while(keepRunning) { 12 System.out.println(getName() + "登台演出:" + (++count)); 13 14 if(count == 100) { 15 keepRunning = false; 16 } 17 18 if(count % 10 == 0) { 19 try { 20 Thread.sleep(1000); 21 } catch (InterruptedException e) { 22 // TODO Auto-generated catch block 23 e.printStackTrace(); 24 } 25 } 26 27 } 28 29 System.out.println(getName() + "的演出结束了!"); 30 } 31 32 public static void main(String args[]) { 33 Thread actor = new Actor(); 34 actor.setName("Mr.Thread"); 35 36 actor.start(); 37 38 Thread actressThread = new Thread(new Actress(),"Ms.Runnable"); 39 actressThread.start(); 40 } 41 42 } 43 44 45 class Actress implements Runnable{ 46 47 @Override 48 public void run() { 49 System.out.println(Thread.currentThread().getName() + "是一个演员!"); 50 int count = 0; 51 boolean keepRunning = true; 52 53 while(keepRunning) { 54 System.out.println(Thread.currentThread().getName() + "登台演出:" + (++count)); 55 56 if(count == 100) { 57 keepRunning = false; 58 } 59 60 if(count % 10 == 0) { 61 try { 62 Thread.sleep(1000); 63 } catch (InterruptedException e) { 64 // TODO Auto-generated catch block 65 e.printStackTrace(); 66 } 67 } 68 69 } 70 71 System.out.println(Thread.currentThread().getName() + "的演出结束了!"); 72 } 73 }