contextswitchtest.java

来自「SRI international 发布的OAA框架软件」· Java 代码 · 共 57 行

JAVA
57
字号
import edu.emory.mathcs.backport.java.util.concurrent.*;
import edu.emory.mathcs.backport.java.util.concurrent.locks.*;
import edu.emory.mathcs.backport.java.util.concurrent.atomic.*;
import edu.emory.mathcs.backport.java.util.concurrent.helpers.*;
import java.util.*;

public final class ContextSwitchTest {
    final static int iters = 1000000;
    static AtomicReference turn = new AtomicReference();
    public static void main(String[] args) throws Exception {
//        MyThread a = new MyThread();
//        MyThread b = new MyThread();
//        a.other = b;
//        b.other = a;
//        turn.set(a);
//        long startTime = Utils.nanoTime();
//        a.start();
//        b.start();
//        a.join();
//        b.join();
//        long endTime = Utils.nanoTime();
//        int np = a.nparks + b.nparks;
//        System.out.println((endTime - startTime) / np);
    }

    private static int nextRandom(int x) {
        int t = (x % 127773) * 16807 - (x / 127773) * 2836;
        return (t > 0)? t : t + 0x7fffffff;
    }

    static final class MyThread extends Thread {
//        volatile Thread other;
//        volatile int nparks;
//        volatile int result;
//
//        public void run() {
//            int x = 17;
//            int p = 0;
//            for (int i = 0; i < iters; ++i) {
//                while (!turn.compareAndSet(other, this)) {
//                    LockSupport.park();
//                    ++p;
//                }
//                x = nextRandom(x);
//                LockSupport.unpark(other);
//            }
//            LockSupport.unpark(other);
//            nparks = p;
//            result = x;
//            System.out.println("parks: " + p);
//
//        }
    }
}


⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?