ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/loops/ContextSwitchTest.java
Revision: 1.2
Committed: Mon May 9 19:33:30 2005 UTC (19 years ago) by dl
Branch: MAIN
Changes since 1.1: +6 -0 lines
Log Message:
Add headers

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/licenses/publicdomain
5 */
6
7 import java.util.concurrent.*;
8 import java.util.concurrent.locks.*;
9 import java.util.concurrent.atomic.*;
10 import java.util.*;
11
12 public final class ContextSwitchTest {
13 final static int iters = 1000000;
14 static AtomicReference turn = new AtomicReference();
15 public static void main(String[] args) throws Exception {
16 MyThread a = new MyThread();
17 MyThread b = new MyThread();
18 a.other = b;
19 b.other = a;
20 turn.set(a);
21 long startTime = System.nanoTime();
22 a.start();
23 b.start();
24 a.join();
25 b.join();
26 long endTime = System.nanoTime();
27 int np = a.nparks + b.nparks;
28 System.out.println((endTime - startTime) / np);
29 }
30
31 private static int nextRandom(int x) {
32 int t = (x % 127773) * 16807 - (x / 127773) * 2836;
33 return (t > 0)? t : t + 0x7fffffff;
34 }
35
36 static final class MyThread extends Thread {
37 volatile Thread other;
38 volatile int nparks;
39 volatile int result;
40
41 public void run() {
42 int x = 17;
43 int p = 0;
44 for (int i = 0; i < iters; ++i) {
45 while (!turn.compareAndSet(other, this)) {
46 LockSupport.park();
47 ++p;
48 }
49 x = nextRandom(x);
50 LockSupport.unpark(other);
51 }
52 LockSupport.unpark(other);
53 nparks = p;
54 result = x;
55 System.out.println("parks: " + p);
56
57 }
58 }
59 }
60
61