2003-12-26 Guilhem Lavaux <guilhem@kaffe.org>
[official-gcc.git] / libjava / testsuite / libjava.lang / TLtest.java
blobb7f4115b23fbb91493fa81871a4db955c6a77010
1 class TLtest extends Thread {
3 public static void main (String [] args) {
4 Data d = new Data ();
5 new ThreadTest (d, "A").start ();
6 new ThreadTest (d, "B").start ();
10 class Data {
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 {
25 public Data d;
27 ThreadTest (Data d, String name) {
28 super (name);
29 this.d = d;
32 public void run () {
34 int value = 0;
35 int ref = 0;
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));
48 try {
49 sleep((int)(Math.random() * 500));
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 */
55 if (ref == value)
56 System.out.println ("test OK.");
57 else
58 System.out.println ("test failed.");