執行緒問題2(注意例項變數)

chinayuan發表於2020-04-05
 這個例子就是為了說明instance和static變數被多個執行緒訪問的結果:

1.static 的話,肯定要注意多執行緒的問題
2.instance的話,就看前面caller的程式碼怎麼寫了。
  在多個執行緒的情況下,instance 變數很可能被多個執行緒修改過。
3.sychronized僅僅是為了保證原子操作性,對變數被多執行緒訪問過是無法控制的

package com.tools.thread.eighth;

public class MultipleThreadTest {
    public static void main(String[] args) {
       
        final Call1 call1 = new Call1();
       
        for (int i = 0; i < 100; i++) {
            Thread  Work = new Thread() {
                public void run() {
                    //下面的註釋可以去掉,察看不同的執行結果
                   
//                    call1.synchronous();
                    call1.asynchronous();
//                    call1.call();
                }
            };
           
            Work.start();
        }
       
       
        try {
            Thread.currentThread().sleep(500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


package com.tools.thread.eighth;

public class Call1 {
   
    private Call2 call2 = new Call2();
   
    synchronized void synchronous(){
        call2.print();
    }
   
    void asynchronous(){
       
       call2.print();
    }
   
    void call(){
        Call2 call3 = new Call2();
        call3.print();
     }
}


package com.tools.thread.eighth;

public class Call2 {
    private String sharedInstanceResoure = "instanceResource" ;
   
    private static String sharedStaticResouce = "staticResource" ;
   
    public void print(){
        setResource(getResource()+ " "+ Thread.currentThread().getName());       
        System.out.println(Thread.currentThread().getName()+ ":"+getResource());
       
        setStaticResource(getStaticResource()+ " "+ Thread.currentThread().getName());       
        System.out.println(Thread.currentThread().getName()+ ":"+getStaticResource());
    }

    public String getResource() {
        return sharedInstanceResoure;
    }

    public void setResource(String resource) {
        this.sharedInstanceResoure = resource;
    }
   
    public String getStaticResource() {
        return sharedStaticResouce;
    }

    public void setStaticResource(String resource) {
        this.sharedStaticResouce = resource;
    }
   
}



相關文章