1. 程式人生 > >多線程 小例子

多線程 小例子

set rgs 退出 開始 rri let 重新 ted 處理

1. 線程小例子
 /**
 * 失去一日甚易,欲得回已無途!
 *                     2016-11-17下午1:43:51
 * 
 * 進程:可以包含一個或者多個線程!  cpu上  真正 執行的 是 線程!
 * 
 *   實現多線程的方法:
 *    01.繼承Thread類            重寫run()
 *    02.實現Runnable接口   重寫run()
 * 
 * 多線程:在單個程序中,同時運行多個線程來完成不同的工作! 多個線程   並發   執行的技術!
 * 
 * 並發:在同一個時間段中 有幾個程序 都處於 啟動運行 到 運行完畢 之間!
 *      計算機同時運行幾個程序,或者運行同一個程序的多個進程或者線程!
 *      各就各位  ,預備!  跑!
 *         運動員的狀態???   並發!               
 *       秋季 是感冒的高發期!   
 *  
 * 在一個確定的事件點! 只能有一個線程在執行!                   
 *                     
 * run()和start()區別:
 *      run():就是類中的一個普通方法,如果兩個類中都有run(),那麽肯定是一個run()執行完畢之後才會執行另一個run();
 *      修飾符必須是public! 返回值類型 必須是 void!           
 *      
 *      start():只有執行start()才算是啟動線程!這是一個就緒狀態!默認會執行run();無需等待run()中的內容全部執行完畢!  
 *       在調用start()並沒有立即執行run()!而是在一個不確切的時間執行!cpu分配時間片給當前線程時,
 *       當前線程才執行run()裏面的代碼!
 * 
 * 線程的生命周期:
 * 1.新生
 * Thread01 thread01=new Thread01();
 * 2.就緒
 *  thread01.start();        
 * 3.運行
 *  cpu分配時間片給thread01的時候,執行run()
 * 4.阻塞
 *  sleep(); wait()
 * 5.死亡
 *   001.正常    run()執行完畢後   正常的退出
 *   002.異常  run()執行的過程中,出現異常情況,非正常的退出!
 *   
 *線程的優先級!
 *   默認值  是 5,最小值 1, 最大值  10!
 *   thread01.setPriority(9);
 */
public class MyThread {
    public static void main(String[] args) {
        //創建第一個線程  繼承了 Thread
        Thread01 thread01=new Thread01();
        thread01.setName("當前線程--1");
        thread01.start();
        System.out.println("**************");
        //創建第二個線程   實現了Runnable
        Thread thread02=new Thread(new Thread02());
        thread02.setPriority(9);  //設置優先級
        thread02.setName("當前線程--2");
        thread02.start();
        
    }

}

//01. 繼承Thread  重寫run()
class  Thread01  extends Thread{
     private  int  count;
     //輸出0-100之間的偶數和
     public void run(){
         while (count<=100) {
            if (count%2==0) {
                // 獲取當前正在執行的線程  Thread.currentThread()
                System.out.println(Thread.currentThread().getName()+":"+count);
            }
            count++;
        }
     }
}


//02. 實現Runnable接口 重寫run()
class  Thread02 implements Runnable{
     private  int  count;
     //輸出0-100之間的偶數和
     public void run(){
         while (count<=100) {
            if (count%2==0) {
                // 獲取當前正在執行的線程  Thread.currentThread()
                System.out.println(Thread.currentThread().getName()+":"+count);
            }
            count++;
        }
     }
}

2.同步代碼方法 實現賣票
public class SaleTicket implements Runnable{
     //庫存票數
     private  int   tickets=100;
    
    /*
     * 賣票  同步代碼方法 比 同步代碼塊 性能高!  但是功能是一致的!
     * 一個類中可以有多個 同步方法 或者同步代碼塊
     * 
     * 當 一個對象調用這個對象中的同步方法時!  還可以同時調用其他的同步方法!  無需等待!
     * 但是  一個對象執行這個對象中的同步代碼塊! 這個對象中的所有同步代碼塊 都上鎖了! 都必須等待!
     * 
     * 同步代碼塊 鎖的是 對象  並不是 代碼塊!
     * 
     */
     private synchronized  void  sale(){
         if (tickets>0) {
            System.out.println(Thread.currentThread().getName()+"賣出了"+tickets+"票");
            //票數-1
            tickets--;
        }
         try {
            Thread.sleep(2);  //讓cpu重新分配時間片
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
     }

    @Override
    public void run() {
         while (tickets>0) {
            sale();
        }
    }

    public static void main(String[] args) {
        SaleTicket ticket=new SaleTicket();
        Thread t1=new Thread(ticket);
        Thread t2=new Thread(ticket);
        Thread t3=new Thread(ticket);
        Thread t4=new Thread(ticket);
        //設置窗口名稱
        t1.setName("1號窗口");
        t2.setName("2號窗口");
        t3.setName("3號窗口");
        t4.setName("4號窗口");
        //開始賣票
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        
    }  
}

3.同步代碼塊方法實現賣票
public class SaleTicket implements Runnable{
     //庫存票數
     private  int   tickets=100;
    
    /*
     * 但是  一個對象執行這個對象中的同步代碼塊! 這個對象中的所有同步代碼塊 都上鎖了! 都必須等待!
     * 
     * 同步代碼塊 鎖的是 對象  並不是 代碼塊!
     * 
     */
publicclass SaleTicket implements Runnable{
    private int count = 100;//庫存票數
    @Override
public void run() {
while (count > 0) {
   //同步代碼塊
synchronized (this) {
System.out.println(Thread.currentThread().getName() + "賣出了第"
+ count + "張票。");
count--;
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} public static void main(String[] args) { SaleTicket ticket=new SaleTicket(); Thread t1=new Thread(ticket); Thread t2=new Thread(ticket); Thread t3=new Thread(ticket); Thread t4=new Thread(ticket); //設置窗口名稱 t1.setName("1號窗口"); t2.setName("2號窗口"); t3.setName("3號窗口"); t4.setName("4號窗口"); //開始賣票 t1.start(); t2.start(); t3.start(); t4.start(); } }

4.小總結 /* Runnable Thread Callable Future 多線程 Runnable 與 Callable 區別 01.Runnable默認規定執行的方法時run();Callable默認規定執行的方法時call(); 02.Runnable的run()沒有返回值,Callable中的call()具有返回值 03.run()不能聲明異常!必須內部處理! call()可以聲明異常 04.運行Callable的時候可以 拿到一個Future對象 ! Future是一個模式! 核心思想====》 原本需要等待的時間段,現在可以去做一些其他的業務邏輯! 假設 現在有一個 具有返回值的A() 還有一個B() 和C() 之前我們調用A() 必須等待A()返回結構之後 才能調用 B()或者C() 現在我們調用A() 不須等待A()返回結構之後 也能調用 B()或者C() Future */

技術分享 5.驗證同步方法的鎖
public class A implements Runnable {

    //這個方法  其他 線程也可以進入
   public synchronized  void  test(){
       System.out.println("開始......");
       try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
       System.out.println("結束......");
   
   } 
    
    @Override
    public void run() {
        test();
    } 
    
    public static void main(String[] args) {
        for (int i = 1; i <=5; i++) {
            Thread thread=new Thread(new A());
            thread.start();
        }          
    }

}

驗證同步方法的鎖 技術分享 6.驗證同步代碼塊的鎖
public class A implements Runnable {

    //驗證同步代碼庫鎖的是 當前對象
     public   void  test(){
            synchronized (this) {
                   System.out.println("開始......");
                   try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                   System.out.println("結束......");
            }
           
           }
    
    @Override
    public void run() {
        test();
    }
    
    
    public static void main(String[] args) {
        A a=new A();
        for (int i = 1; i <=5; i++) {
            Thread thread=new Thread(a);
            thread.start();
        }
    }
}

多線程 小例子