阅读背景:

多线程共享资源的同步是更好的选择吗?

来源:互联网 
public class MyResource {

private int count = 0;

void increment() {

    count++;

}

void insert() {    // incrementing shared resource count
    for (int i = 0; i < 100000000; i++) {
        increment();
    }

}

void insert1() {       //incrementing shared resource count
    for (int i = 0; i < 100000000; i++) {
        increment();
    }

}

void startThread() {

    Thread t1 = new Thread(new Runnable() {  //thread incrementing count using insert()

        @Override
        public void run() {
            insert();
        }
    });

    Thread t2 = new Thread(new Runnable() {    //thread incrementing count using insert1()

        @Override
        public void run() {
            insert1();
        }
    });

    t1.start();
    t2.start();

    try {
        t1.join(); //t1 and t2 race to increment count by telling current thread to wait
        t2.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

void entry() {
    long start = System.currentTimeMillis();
    startThread();            //commenting insert(); insert1() gives output as time taken = 452(approx)   110318544  (obvious)

    // insert(); insert1();     //commenting startThread() gives output as time taken = 452(approx)   200000000

    long end = System.currentTimeMillis();
    long time = end - start;
    System.out.println("time taken = " + time);

    System.out.println(count);
}
public class MyResource {

private int count = 



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: