執行緒範圍內共享資料ThreadLocal

2021-09-20 06:29:05 字數 1537 閱讀 8960

//原始碼:

private t setinitialvalue()

1、原始版本:

public class threadlocaltestbefore 

}).start();

new thread(new runnable()

}).start();

}//a、b類分別為使用執行緒區域性變數的資料

static class a

}static class b

}}//儲存執行緒區域性變數的類

class threadlocaldata

public string getname()

public void setname(string name)

public int getage()

public void setage(int age)

}

2、改良版本:

改良原因:因為每個執行緒該區域性變數只有乙個,所以可以把該物件設計為單例模式,並封裝在內部。

public class threadlocaltest 

}).start();

new thread(new runnable()

}).start();

}//a、b類分別為使用執行緒區域性變數的資料

static class a

}static class b

}}//模仿單例設計模式

class threadlocaldata;

//已設計成執行緒內資料共享模式

public static threadlocaldata getthreadinstance()

return instance;

}private string name;

private int age;

public string getname()

public void setname(string name)

public int getage()

public void setage(int age)

}

最常見的threadlocal使用場景為 用來解決 資料庫連線(不考慮連線池)、session管理等。

private static threadlocalconnectionholder = new threadlocal() }; 

public static connection getconnection()

private static final threadlocal threadsession = new threadlocal();

public static session getsession() throws infrastructureexception

} catch (hibernateexception ex)

return s;

}

執行緒範圍內共享資料

我們可以先用所學知識來寫乙個 public class threadscopesharedata start static class a static class b 如果光像上面這樣寫的話,那毫無疑問,肯定是有問題的,如下圖所示並沒有實現執行緒共享 此時就實現執行緒內共享資料了 public c...

執行緒範圍內共享資料

假設現在有個公共的變數data,有不同的執行緒都可以去操作它,如果在不同的執行緒對data操作完成後再去取這個data,那麼肯定會出現執行緒間的資料混亂問題,因為a執行緒在取data資料前可能b執行緒又對其進行了修改,下面寫個程式來說明一下該問題 public class threadscopesh...

執行緒範圍內共享資料的例子

設計四個執行緒,其中兩個執行緒每次給增加j增加一,另外兩個給j減一。設計四個執行緒,其中兩個執行緒每次給增加i增加一,另外兩個給i減一。方式一 呼叫兩個繼承了runnable類的類進行資料的加減操作 public class threadscopedatatest static class incr...