首页 > 代码库 > java 多线程机制

java 多线程机制

技术分享

 

技术分享

技术分享

 

 

技术分享

 

技术分享

技术分享

 

Example12_1.java

public class Example12_1 { 
   public  static void main(String args[]) { //主线程
       SpeakElephant  speakElephant;
       SpeakCar  speakCar;  
       speakElephant = new SpeakElephant() ;      //创建线程
       speakCar = new SpeakCar();                //创建线程
       speakElephant.start();                          //启动线程 
       speakCar.start();                         //启动线程
       for(int i=1;i<=15;i++) {
          System.out.print("主人"+i+"  ");
       }  
   }
}

SpeakElephant.java

public class SpeakElephant extends Thread {
   public void run() {
      for(int i=1;i<=20;i++) {
         System.out.print("大象"+i+"  ");
      }  
   } 
}

SpeakCar.java

public class SpeakCar extends Thread {
   public void run() {
      for(int i=1;i<=20;i++) {
         System.out.print("轿车"+i+"  ");
      }  
   } 
}

 

技术分享

Example12_2.java

public class Example12_2 { 
   public static void main(String args[]) { 
       Thread speakElephant;            //用Thread声明线程
       Thread speakCar;                 //用Thread声明线程
       ElephantTarget elephant;         //speakElephant线程的目标对象
       CarTarget car;                   //speakCar线程的目标对象
       elephant = new ElephantTarget();
       car = new CarTarget();
       speakElephant = new Thread(elephant) ;   //创建线程
       speakCar = new Thread(car);              //创建线程
       speakElephant.start();                    //启动线程 
       speakCar.start();                        //启动线程
       for(int i=1;i<=15;i++) {
          System.out.print("主人"+i+"  ");
       }  
   }
}

ElephantTarget.java

public class ElephantTarget implements Runnable {
   public void run() {
      for(int i=1;i<=20;i++) {
         System.out.print("大象"+i+"  ");
      }  
   } 
}

CarTarget.java

public class CarTarget implements Runnable {
   public void run() {
      for(int i=1;i<=20;i++) {
         System.out.print("轿车"+i+"  ");
      }  
   } 
}

 

java 多线程机制