summaryrefslogtreecommitdiff
path: root/libjava/testsuite/libjava.lang/Thread_Monitor.java
blob: 649a75c762c1d3d70e7f3d297903e38f0103b3cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Test that monitor locks work and are recursive.

class T implements Runnable
{
  public int count = 0;
  Counter c;
  
  public T (Counter c)
  {
    this.c = c;
  }

  public void run()
  {
    while (true)
      {
        // NOTE: double-synchronization here.
	synchronized (c)
	{
	  if (c.getCount() <= 100000)
	    count++;
	  else
	    break;
	}
      }
  }
}

class Counter
{
  int i = 0;
  public synchronized int getCount ()
  {
    return ++i; 
  }
}

public class Thread_Monitor
{
  public static void main(String args[])
  {
    Counter c = new Counter();
    T t1 = new T(c);
    T t2 = new T(c);
    
    Thread th1 = new Thread(t1);
    Thread th2 = new Thread(t2);
    th1.start();
    th2.start();
    try
    {
      th1.join();
      th2.join();
    } 
    catch (InterruptedException x)
    {
      System.out.println("failed: Interrupted");
    }
    if (t1.count + t2.count == 100000)
      System.out.println ("ok");
    else
      System.out.println ("failed: total count incorrect");
  }
}