java多線程詳解

1、傳統線程機制的回顧java

  1.一、繼承Thread類緩存

Thread thread1 = new Thread(){
   public void run() {
    while(true){
     try {
      Thread.sleep(1000);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
     System.out.println("chenweisong");
    }
   }
  };
  
  thread1.start();

 

1.二、實現Runnable接口ide

Thread thread2 = new Thread(new Runnable(){
   public void run() {
    while(true){
     try {
      Thread.sleep(1000);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
     System.out.println("chenweisong");
    }
   }
   
  });
  thread2.start();

 

1.三、Timer類和TimerTask類的應用oop

  Timer timer1 = new Timer();
  timer1.schedule(new TimerTask(){
   public void run() {
    System.out.println("bombing!!!!");
   }
   
  }, 2000);
  while(true){
   System.out.println(new Date().getSeconds());
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

  1.4 線程的同步互斥與通信spa

final Output output = new Output();

  new Thread(new Runnable(){

   public void run() {

    while(true){

     try {

      Thread.sleep(500);

      output.outprint("chenweisong");

     } catch (Exception e) {

      e.printStackTrace();

     }

    }

   }

   

  }).start();

  

  

  new Thread(new Runnable(){

   public void run() {

    while(true){

     try {

      Thread.sleep(500);

      Output.outprint2("wuyouyi");

     } catch (Exception e) {

      e.printStackTrace();

     }

    }

   }

   

  }).start();

  

  

 }

 

 static class Output{

  public  void outprint(String s){

   synchronized(Output.class){

    for(int i =0;i<s.length();i++){

     System.out.print(s.charAt(i));

    }

    System.out.println();

   }

   

  }

  

  

  public synchronized static void outprint2(String s){

   for(int i =0;i<s.length();i++){

    System.out.print(s.charAt(i));

   }

   System.out.println();

  }

 }

 2、java5線程池方式線程

 

l線程池的概念與Executors類的應用code

 

**

 * 步驟1:用3個大小的固定線程池去執行10個內部循環10次就結束的任務,

 * 爲了觀察固定線程池下的其餘任務一直再等待,但願打印出正在執行的線程名、

 * 任務序號和任務內部的循環次數,剛開始看到只有3個線程在執行,

 * 並看到任務前仆後繼的效果。注意:這10個任務要用各自獨立的runnable對象,才能看到任務的序號。

步驟2:改成緩存線程池,能夠看到當前有多少個任務,就會分配多少個線程爲之服務。

//ExecutorService  ThreadPool = Executors.newFixedThreadPool(3);

  ExecutorService  ThreadPool = Executors.newCachedThreadPool();//改成緩存線程池

   for (int i = 1; i <= 10; i++) {

    final int task=i;

    ThreadPool.execute(new Runnable(){

    public void run() {

     try {

      //Thread.sleep(100);

      for(int j=1; j<=10; j++){

       System.out.println(Thread.currentThread().getName()+" executor task "+task+" loop of "+j);

      }

     } catch (Exception e) {

      e.printStackTrace();

     }

    }

     

    });

  }

   ThreadPool.shutdown();
  /**

   * 用下面這句代碼來講明上面的代碼是在提交任務,

   * 而且全部的任務都已經提交了,

   * 但任務是何時執行的,則是由線程池調度的!

   */

  ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

  scheduledExecutorService.schedule(//隔多久後執行一次

    new Runnable(){

     public void run() {

      System.out.println("bombing!!!!");

     }

     

    }, 

    3,

    TimeUnit.SECONDS);

  

  scheduledExecutorService.scheduleAtFixedRate(//隔多久後執行一次,之後每隔多久執行一次

    new Runnable(){

     public void run() {

      System.out.println("bombing!!!!");

     }

     

    }, 

    3,

    1,

    TimeUnit.SECONDS);

Lock&Condition實現線程同步通訊對象

如下例子爲,三個線程輪流作一件事情繼承

 
package TradicationThreadTest;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreeConditionCommunication {
 /**
  * @param args
  */
 public static void main(String[] args) {
  
  final Business business = new Business();
  new Thread(
    new Runnable() {
     
     @Override
     public void run() {
     
      for(int i=1;i<=50;i++){
       business.sub2(i);
      }
      
     }
    }
  ).start();
  
  new Thread(
    new Runnable() {
     
     @Override
     public void run() {
     
      for(int i=1;i<=50;i++){
       business.sub3(i);
      }
      
     }
    }
  ).start();  
  
  for(int i=1;i<=50;i++){
   business.main(i);
  }
  
 }
 static class Business {
   Lock lock = new ReentrantLock();
   Condition condition1 = lock.newCondition();
   Condition condition2 = lock.newCondition();
   Condition condition3 = lock.newCondition();
    private int shouldSub = 1;
    public  void sub2(int i){
     lock.lock();
     try{
      while(shouldSub != 2){
       try {
      condition2.await();
     } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
      }
     for(int j=1;j<=10;j++){
      System.out.println("sub2 thread sequence of " + j + ",loop of " + i);
     }
      shouldSub = 3;
      condition3.signal();
     }finally{
      lock.unlock();
     }
    }
    public  void sub3(int i){
     lock.lock();
     try{
      while(shouldSub != 3){
       try {
      condition3.await();
     } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
      }
     for(int j=1;j<=20;j++){
      System.out.println("sub3 thread sequence of " + j + ",loop of " + i);
     }
      shouldSub = 1;
      condition1.signal();
     }finally{
      lock.unlock();
     }
    }    
    
    public  void main(int i){
     lock.lock();
     try{
     while(shouldSub != 1){
        try {
       condition1.await();
      } catch (Exception e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
       }
     for(int j=1;j<=100;j++){
      System.out.println("main thread sequence of " + j + ",loop of " + i);
     }
     shouldSub = 2;
     condition2.signal();
    }finally{
     lock.unlock();
    }
   }
 
 }
}
相關文章
相關標籤/搜索