一個多執行緒的程式如果是透過Runnable介面實現的,則表示類別中的屬性將被多個執行緒共用


package pkg9.pkg19;

class MyThread implements Runnable{
    private int ticket = 5;
    public void run(){
        for(int i = 0 ; i < 100 ; i++){
            if(ticket > 0){
                try{
                Thread.sleep(1000);
                }catch(InterruptedException ex){}
                System.out.println("賣票 目前有" + ticket-- + "票");
                
            }
        }
    }
}
public class Main {

    public static void main(String[] args) {
        MyThread mt = new MyThread();
        Thread t1 = new Thread(mt);
        Thread t2 = new Thread(mt);
        Thread t3 = new Thread(mt);
        t1.start();
        t2.start();
        t3.start();
    }
}
 


run:
賣票 目前有4票
賣票 目前有3票
賣票 目前有5票
賣票 目前有2票
賣票 目前有1票
賣票 目前有1票
賣票 目前有0票
BUILD SUCCESSFUL (total time: 3 seconds)

 


同步就是指多個操作在同一個時間段內只能有一個執行緒執行,其他執行緒要等待此執行緒完成之後才可以繼續執行。


package pkg9.pkg19;

class MyThread implements Runnable {

    private int ticket = 5;

    public void run() {
        for (int i = 0; i < 100; i++) {
            //同步程式碼區塊
            synchronized (this) {
                if (ticket > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                    }
                    System.out.println("賣票 目前有" + ticket-- + "票");
                }
            }
        }
    }
}

public class Main {

    public static void main(String[] args) {
        MyThread mt = new MyThread();
        Thread t1 = new Thread(mt);
        Thread t2 = new Thread(mt);
        Thread t3 = new Thread(mt);
        t1.start();
        t2.start();
        t3.start();
    }
}
 


run:
賣票 目前有5票
賣票 目前有4票
賣票 目前有3票
賣票 目前有2票
賣票 目前有1票
BUILD SUCCESSFUL (total time: 5 seconds)
 

arrow
arrow
    文章標籤
    Java
    全站熱搜
    創作者介紹
    創作者 mingyilai 的頭像
    mingyilai

    mingyilai的部落格

    mingyilai 發表在 痞客邦 留言(0) 人氣()