Java線程總結(二)

自定義線程的數據能夠共享,也能夠不共享,這要看具體的實現方式。多線程

1.不共享數據多線程實現方式:ide

public class MyThread  extends Thread{
    private int count = 4;

    public MyThread(String threadName){
        this.setName(threadName);
    }

    @Override
    public void run(){
        while (count > 0){
            count = count - 1;
            System.out.println("由 " + Thread.currentThread().getName() + " 計算,count = " + count);
            try {
                Thread.sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        MyThread threadA = new MyThread("A");
        MyThread threadB = new MyThread("B");
        MyThread threadC = new MyThread("C");
        threadA.start();
        threadB.start();
        threadC.start();
    }
}

執行結果以下:this

從結果上看,每一個線程都是都是先打印3,再打印2,而後是1,0。由此可知各個線程都有一份變量count,不受其餘線程的干擾。spa

2. 共享數據的多線程實現方式線程

public class MyThread  extends Thread{
    private int count = 4;

    @Override
    public void run(){
        while (count > 0){
            count = count - 1;
            System.out.println("由 " + Thread.currentThread().getName() + " 計算,count = " + count);
            try {
                Thread.sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        Thread a = new Thread(myThread,"A");
        Thread b = new Thread(myThread,"B");
        Thread c = new Thread(myThread,"C");
        Thread d = new Thread(myThread,"D");
        a.start();
        b.start();
        c.start();
        d.start();
    }
}

執行結果以下:code

由結果可知,A,B,C,D四個線程共享變量countblog

相關文章
相關標籤/搜索