JAVA 多线程同步工具类总结(二)

2014-11-24 10:43:50 · 作者: · 浏览: 1
"Future task started...");
Thread.sleep(5000);
System.out.println("Future task finished...");
return new Movie("2012","Unknown");
}

});

// 在子线程中启动任务
Thread thread = new Thread(future);
thread.start();

// 主线程干点别的事情
System.out.println("Now let's do sth eles...");
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}

// 主线程开始取结果
System.out.println("Now wait for result of future task...");
try {
Movie res = future.get();
System.out.printf("Result from task is name=%s, actor=%s", res.name, res.actor);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}

}

public static class Movie {
final public String name;
final public String actor;
public Movie(String name, String actor) {
this.name = name;
this.actor = actor;
}
}

}

Semaphore 的例子:
[java]
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

public class DemoOfSemaphore {

/**
* @param args
*/
public static void main(String[] args) {

final int numOfThread = 5;
final AtomicInteger count = new AtomicInteger(0); // 用于分配唯一线程标识
final Semaphore semaphore = new Semaphore(numOfThread); // 用于控制并发线程数目

for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new Runnable() {

@Override
public void run() {
int tid = count.getAndIncrement();
try {
// 等待直到取得信号量
System.out.printf("Thread %d wait on semaphore...%n", tid);
semaphore.acquire();
// 取得信号量之后做点事情
System.out.printf("Thread %d get semaphore...%n", tid);
int duration = (int)(Math.random() * 5000);
Thread.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 做完后释放信号量
System.out.printf("Thread %d release semaphore...%n", tid);
semaphore.release();
}

}

});
thread.start();
}

}

}

CyclicBarrier 的例子:
[java] view plaincopy
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class DemoOfBarrier {

public static void main(String[] args) {

final int numOfThread = 2;
final int numOfIteration = 2;

// 创建一个用于线程同步的 Barrier 对象
final CyclicBarrier barrier = new CyclicBarrier(numOfThread,
new Runnable() {

// 当所有线程到达 Barrier 后会执行这个任务
// 任务在第一个 到达 Barrier 的线程中执行
@Override
public void