import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.atomic.AtomicLong;
/**
* Java線程:新特徵-原子量
*
* @author leizhimin 2009-11-6 9:53:11
*/
public
class Test {
public
static
void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
Lock lock =
new ReentrantLock(
false);
Runnable t1 =
new MyRunnable(
"張三", 2000,lock);
Runnable t2 =
new MyRunnable(
"李四", 3600,lock);
Runnable t3 =
new MyRunnable(
"王五", 2700,lock);
Runnable t4 =
new MyRunnable(
"老張", 600,lock);
Runnable t5 =
new MyRunnable(
"老牛", 1300,lock);
Runnable t6 =
new MyRunnable(
"胖子", 800,lock);
//執行各個線程
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
pool.execute(t6);
//關閉線程池
pool.shutdown();
}
}
class MyRunnable
implements Runnable {
private
static AtomicLong aLong =
new AtomicLong(10000);
//原子量,每一個線程均可以自由操做
private String name;
//操做人
private
int x;
//操做數額
private Lock lock;
MyRunnable(String name,
int x,Lock lock) {
this.name = name;
this.x = x;
this.lock = lock;
}
public
void run() {
lock.lock();
System.out.println(name +
"執行了" + x +
",當前餘額:" + aLong.addAndGet(x));
lock.unlock();
}
}