1. 程式人生 > >Java線程總結(二)

Java線程總結(二)

@override end system interrupt clas this trace trac inf

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

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

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(); } }

執行結果如下:

技術分享圖片

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

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(); } }

執行結果如下:

技術分享圖片

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

Java線程總結(二)