50,530
社区成员
发帖
与我相关
我的任务
分享
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class TestAB {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(1);
ExecutorService es = Executors.newFixedThreadPool(2);
es.submit(new Worker("A", countDownLatch));
es.submit(new Worker("B", countDownLatch));
es.shutdown();
try {
// 等待10秒超时
countDownLatch.await(10, TimeUnit.SECONDS);
if (countDownLatch.getCount() > 0) {
System.out.println("Worker A & B do not compelete their work.");
} else {
System.out.println("Worker A | B has compeleted his work.");
}
System.out.println("Main thread done!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Worker implements Runnable {
private String name;
private final CountDownLatch countDownLatch;
public Worker(String name, CountDownLatch countDownLatch) {
this.name = name;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
// 模拟执行任务,随机 7 ~ 12秒
long start = System.currentTimeMillis();
int sleep = 7 + new Random().nextInt(5);
try {
Thread.sleep(sleep * 1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + " has done his work!");
System.out.println(name + " elapsed: " + (System.currentTimeMillis() - start));
countDownLatch.countDown();
}
}
class MyRunnable implements Runnable {
private int i = 0;
@Override
public void run() {
// TODO Auto-generated method stub
while (i < 10) {
System.out.println(Thread.currentThread().getName() + ":" + i);
i++;
}
if(i==10){
System.out.println("---------"+Thread.currentThread().getName()+"唤醒主线程-------------");
synchronized (Test1.obj) {
Test1.obj.notify();
}
}
}
}
class MainThread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (Test1.obj) {
System.out.print("主线程开始运行。。。。 ");
try {
System.out.println("主线程被挂起10s。。。。");
Test1.obj.wait(10*1000);
System.out.println("主线程继续运行。。。。");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//测试类
public class Test1 {
public static final Object obj = new Object();
public static void main(String[] args) {
// TODO Auto-generated method stub
new Thread(new MainThread()).start();
MyRunnable mr = new MyRunnable();
Thread t1 = new Thread(mr, "A");
Thread t2 = new Thread(mr, "B");
t1.start();
t2.start();
}
}
import java.util.concurrent.Future;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.ArrayList;
public class Test{
public static void main(String[] args){
Task A = new Task("A");
Task B = new Task("B");
Object o = new Object();
Server server = new Server(o,A,B);
Thread serverThread = new Thread(server);
serverThread.start();
synchronized(o){
try{
o.wait(10000);//线程等待10秒
serverThread.interrupt();//中断线程
}catch(InterruptedException e){
e.printStackTrace();
System.exit(1);
}
}
System.out.println("Main: finished!");
}
}
class Task implements Callable<String>{
public Task(String name){
this.name = name;
}
@Override
public String call()throws Exception{
long duration = (long)(Math.random() * 20);//设置随机等待时间.
System.out.printf("%s: Waiting %d seconds for processing!\n",name,duration);
try{
TimeUnit.SECONDS.sleep(duration);
}catch(InterruptedException e){
return null;
}
System.out.printf("%s: Finished!\n",name);
return name;
}
private String name;
}
class Server implements Runnable{
public Server(Object o,Task ... tasks){
this.o = o;
for(Task task : tasks){
taskList.add(task);
}
}
@Override
public void run(){
try{
executor.invokeAny(taskList);
}catch(InterruptedException|ExecutionException e){
}finally{
executor.shutdown();
}
synchronized(o){
o.notifyAll();
}
}
private ExecutorService executor = Executors.newCachedThreadPool();
private List<Task> taskList = new ArrayList<>();
private final Object o;
}
public class Test{
public static void main(String[] args){
Task task = new Task("A");
MyThread threadA = new MyThread(task,"A");
MyThread threadB = new MyThread(task,"B");
threadA.start();
threadB.start();
Object synObject = new Object();
ConditionThread condition = new ConditionThread(synObject,threadA,threadB);
condition.start();//监控线程
synchronized(synObject){
try{
synObject.wait(10000);//主线程等待10秒
}catch(InterruptedException e){
}
//10秒后中断线程A和线程B
threadA.interrupt();
threadB.interrupt();
}
}
}
class ConditionThread extends Thread{
//这个线程是监控线程.一旦发现传入的线程中有某个已经优先完成.那么将中断剩余的线程.
public ConditionThread(Object synObject,MyThread ... threads){
this.threads = threads;
this.synObject = synObject;
}
@Override
public void run(){
while(true){
for(int i = 0 ; i < threads.length ; i ++){
if(threads[i].getCondition()){
for(int j = 0 ; j < i ; j ++ ){
threads[j].interrupt();
}
for(int j = i + 1 ; j < threads.length ; j ++){
threads[j].interrupt();
}
synchronized(synObject){
synObject.notifyAll();
}
return;
}
}
}
}
private MyThread[] threads;
private Object synObject;
}
class MyThread extends Thread{
public MyThread(Runnable task,String name){
super(task,name);
}
@Override
public void run(){
super.run();
condition = true;
}
public boolean getCondition(){
//判断改线程是否已经完成.
return condition;
}
private boolean condition = false;
}
class Task implements Runnable{
public Task(String str){
this.str = str;
}
@Override
public void run(){
long duration = (long)(Math.random() * 50);//注:这里可以时间长些,一旦线程需要的均时间超过10秒,那么main线程等待10秒后将中断该线程
System.out.printf("%s: waiting %d seconds for processing.\n",Thread.currentThread().getName(),duration);
try{
Thread.sleep(duration * 1000);
}catch(InterruptedException e){
return;
}
System.out.printf("%s: finish!\n",Thread.currentThread().getName());
}
private String str;
}
.....
Task A = new Task("A");//相同的任务
Thread a = new Thread(A);//两条不同的子线程去完成一个相同的任务
Thread b = new Thread(A);
a.start();
b.start();
想达到的效果是,a或b谁先完成了就谁去唤醒主线程,主线程不再等待。
有一种方式貌似是可以使用共享对象的方式实现,但是具体不知道要怎么做。