多线程之Future

The Future interface represents the result of an asynchronous computation. Future provides methods to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.

import java.util.concurrent.Future;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;

public class FutureExample {
    public static void main(String[] args) throws Exception {
	System.out.println("Using fixed thread pool:");
	ExecutorService executor = Executors.newFixedThreadPool(2);
	test(executor);

	System.out.println("\nUsing cached thread pool:");
	executor = Executors.newCachedThreadPool();
	test(executor);

	System.out.println("\nUsing single thread executor:");
	executor = Executors.newSingleThreadExecutor();
	test(executor);
    }

    private static void test(ExecutorService executor) 
		   throws ExecutionException, InterruptedException {
	Counter counter = new Counter();

	Future<?> f1 = executor.submit(new Worker(counter, true, 10000));
	Future<?> f2 = executor.submit(new Worker(counter, false, 10000));
        //运行2个版本,上面改成fasle

	// reject new tasks, must call in order to exit VM
	executor.shutdown();

	// wait for termination, much like Thread.join()
	f1.get();
	f2.get();

	System.out.println("Final count: " + counter.getCount());
    }
}

class Counter {
    private AtomicInteger c = new AtomicInteger(0);

    public void increment() {
	c.getAndIncrement();
    }

    public void decrement() {
	c.getAndDecrement();
    }

    public int getCount() {
	return c.get();
    }
}

class Worker implements Runnable {
    private Counter counter;
    private boolean increment;
    private int count;

    public Worker(Counter counter, boolean increment, int count) {
	this.counter = counter;
	this.increment = increment;
	this.count = count;
    }

    public void run() {
	for (int i = 0; i < this.count; i++) {
	    if (increment) {
		this.counter.increment();
	    }
	    else {
		this.counter.decrement();
	    }
	}
    }
}
修改第行,有2个结果:


原文:http://www.xinotes.org/notes/note/1221/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值