1 class TLtest
extends Thread
{
3 public static void main (String
[] args
) {
5 new ThreadTest (d
, "A").start ();
6 new ThreadTest (d
, "B").start ();
12 private static ThreadLocal owner
= new ThreadLocal () {
13 public Object
initialValue () { return ("0"); }
15 /* A thread will call `set' to set a value it wants an instance
16 of Data to associate with it and only it. */
17 synchronized public void set (String v
){owner
.set (v
);}
18 /* A thread will call `get' to get a value it wants an instance
19 of Data to associate with it and only it. */
20 synchronized public String
get (){return (String
)owner
.get();}
23 class ThreadTest
extends Thread
{
27 ThreadTest (Data d
, String name
) {
37 for (int i
= 0; i
< 20; i
++) {
39 int rand
= (int)(Math
.random ()*20);
41 /* Read `value', ref is kept for comparison */
42 value
= Integer
.parseInt (d
.get());
44 /* change `value' and ref by a random number, store `value'. */
45 value
+= rand
; ref
+= rand
;
46 d
.set (Integer
.toString (value
));
49 sleep((int)((Math
.random() * 20)));
50 } catch (InterruptedException e
) {}
53 /* If a thread didn't have private value to attach to the
54 instance of Data, results wouldn't be the same */
56 System
.out
.println ("test OK.");
58 System
.out
.println ("test failed.");