| 1 | class TLtest extends Thread {
|
|---|
| 2 |
|
|---|
| 3 | public static void main (String [] args) {
|
|---|
| 4 | Data d = new Data ();
|
|---|
| 5 | new ThreadTest (d, "A").start ();
|
|---|
| 6 | new ThreadTest (d, "B").start ();
|
|---|
| 7 | }
|
|---|
| 8 | }
|
|---|
| 9 |
|
|---|
| 10 | class Data {
|
|---|
| 11 |
|
|---|
| 12 | private static ThreadLocal owner = new ThreadLocal () {
|
|---|
| 13 | public Object initialValue () { return ("0"); }
|
|---|
| 14 | };
|
|---|
| 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();}
|
|---|
| 21 | }
|
|---|
| 22 |
|
|---|
| 23 | class ThreadTest extends Thread {
|
|---|
| 24 |
|
|---|
| 25 | public Data d;
|
|---|
| 26 |
|
|---|
| 27 | ThreadTest (Data d, String name) {
|
|---|
| 28 | super (name);
|
|---|
| 29 | this.d = d;
|
|---|
| 30 | }
|
|---|
| 31 |
|
|---|
| 32 | public void run () {
|
|---|
| 33 |
|
|---|
| 34 | int value = 0;
|
|---|
| 35 | int ref = 0;
|
|---|
| 36 |
|
|---|
| 37 | for (int i = 0; i < 20; i++) {
|
|---|
| 38 |
|
|---|
| 39 | int rand = (int)(Math.random ()*20);
|
|---|
| 40 |
|
|---|
| 41 | /* Read `value', ref is kept for comparison */
|
|---|
| 42 | value = Integer.parseInt (d.get());
|
|---|
| 43 |
|
|---|
| 44 | /* change `value' and ref by a random number, store `value'. */
|
|---|
| 45 | value += rand; ref += rand;
|
|---|
| 46 | d.set (Integer.toString (value));
|
|---|
| 47 |
|
|---|
| 48 | try {
|
|---|
| 49 | sleep((int)(Math.random() * 500));
|
|---|
| 50 | } catch (InterruptedException e) {}
|
|---|
| 51 | }
|
|---|
| 52 |
|
|---|
| 53 | /* If a thread didn't have private value to attach to the
|
|---|
| 54 | instance of Data, results wouldn't be the same */
|
|---|
| 55 | if (ref == value)
|
|---|
| 56 | System.out.println ("test OK.");
|
|---|
| 57 | else
|
|---|
| 58 | System.out.println ("test failed.");
|
|---|
| 59 | }
|
|---|
| 60 | }
|
|---|