Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitc1818bc

Browse files
thread local example
1 parentd707496 commitc1818bc

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
packagesporadic.thread;
2+
3+
/**
4+
* The ThreadLocal class in Java enables you to create variables that can only
5+
* be read and written by the same thread. Thus, even if two threads are
6+
* executing the same code, and the code has a reference to a ThreadLocal
7+
* variable, then the two threads cannot see each other's ThreadLocal variables.
8+
*
9+
* Since values set on a ThreadLocal object only are visible to the thread who
10+
* set the value, no thread can set an initial value on a ThreadLocal using
11+
* set() which is visible to all threads.
12+
* Instead you can specify an initial value for a ThreadLocal object by
13+
* subclassing ThreadLocal and overriding the initialValue() method. Here is how
14+
* that looks:
15+
*
16+
* private ThreadLocal myThreadLocal = new ThreadLocal<String>() {
17+
* @Override
18+
* protected String initialValue() { return "This is the initial value"; }
19+
* };
20+
*/
21+
22+
publicclassThreadLocalExample {
23+
24+
publicstaticclassMyRunnableimplementsRunnable {
25+
26+
privateThreadLocal<Integer>threadLocal =newThreadLocal<Integer>();
27+
28+
@Override
29+
publicvoidrun() {
30+
threadLocal.set((int) (Math.random() *100D));
31+
try {
32+
Thread.sleep(2000);
33+
}catch (InterruptedExceptione) {
34+
e.printStackTrace();
35+
}
36+
System.out.println("threadLocal.get() is: " +threadLocal.get());
37+
}
38+
39+
publicstaticvoidmain(String...args) {
40+
MyRunnablesharedRunnableInstance =newMyRunnable();
41+
Threadt1 =newThread(sharedRunnableInstance);
42+
Threadt2 =newThread(sharedRunnableInstance);
43+
44+
t1.start();
45+
t2.start();
46+
}
47+
}
48+
49+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp