我试图创建一个测试,我试图强制一个竞争条件(或至少增加其发生的可能性),我已经使用了CountDownLatch.
问题是我得到了java.lang.IllegalMonitorStateException我的CountDownLatch.wait().我肯定在滥用它CountDownLatch,我肯定不会以聪明的方式创建这个测试.
这个简单的代码再现了我的想法和我的问题(我也有一个要点):
import java.util.*;
import java.util.concurrent.*;
public class Example {
private static BusinessLogic logic;
public static void main(String[] args) {
final Integer NUMBER_OF_PARALLEL_THREADS = 10;
CountDownLatch latch = new CountDownLatch(NUMBER_OF_PARALLEL_THREADS);
logic = new BusinessLogic();
// trying to force the race condition
List<Thread> threads = new ArrayList<Thread>(NUMBER_OF_PARALLEL_THREADS);
for (int i=0; i<NUMBER_OF_PARALLEL_THREADS; i++) {
Thread worker = new Thread(new WorkerRunnable(latch));
threads.add(worker);
worker.start();
}
for (int i = 1; i <= NUMBER_OF_PARALLEL_THREADS; …Run Code Online (Sandbox Code Playgroud) 我使用a CountDownLatch来处理两个Java线程.我的班级结构如下:
MainClass.java
ThreadOne.java
ThreadTwo.java
MainClass:
CountDownLatch latch = new CountDownLatch(2);
Thread thread = new Thread(new ThreadOne(latch));
thread.start();
Thread thread1 = new Thread(new ThreadTwo(latch));
thread1.start();
latch.await(20, TimeUnit.SECONDS);
Run Code Online (Sandbox Code Playgroud)
主类等待其他两个线程完成其工作.一旦他们完成工作,它就不会等到超时值(20秒).我的问题是,如果任何线程被破坏或损坏,那么CountDownLatch等待其超时值.有没有办法忽略那个被打断的线程并继续前进而不等待20秒?
我被要求执行一个名为"ping"和"pong"的pingpong游戏(意思是ping之前没有乒乓)10次.意思是,控制台中的最终输出应该是:"ping!(1)","pong!(1)","ping!(2)","pong!(2)"等.
需求是使用信号量,reetrantlock和倒计时锁存器实现gamepingpongthread.
我的问题是打印顺序并不总是如我所要求的那样,我想知道我做错了什么.
这是代码:
// Import the necessary Java synchronization and scheduling classes.
import java.util.concurrent.Semaphore;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
/**
* @class PingPongRight
*
* @brief This class implements a Java program that creates two
* instances of the PlayPingPongThread and start these thread
* instances to correctly alternate printing "Ping" and "Pong",
* respectively, on the console display.
*/
public class PingPongRight
{
/**
* @class SimpleSemaphore
*
* @brief This class provides a simple counting semaphore …Run Code Online (Sandbox Code Playgroud) 在Java中,一旦CountdownLatch达到其状态= 0,它就无法改变它,因此它将永远保持打开状态.我想知道为什么实现者不允许重用CountDownLatch?
下面代码中提到的每个“CompletableFuture.runAsync”都会进行一些计算,我想在每次调用“CompletableFuture.runAsync”时获得结果。或者换句话说,我希望每个“future0,future1,future2,future3”都包含每次调用“CompletableFuture.runAsync”的结果
我怎样才能做到这一点。
*更新:
我的要求是,对于 CompletableFuture.runAsync 的每次调用,我都会进行一些计算,并且应该返回这些值的 ArrayList。在对 CompletableFuture.runAsync 的四次调用之后,我想对返回的 ArrayLists 进行一些进一步的计算。
代码:
if (this.laplaceImgList != null) {
if (!this.laplaceImgList.isEmpty()) {
if (this.laplaceImgList.size() == 3) {
//executor
ExecutorService orintMapExe;
CompletableFuture<Void> future0 = null;
CompletableFuture<Void> future1 = null;
CompletableFuture<Void> future2 = null;
CompletableFuture<Void> future3 = null;
orintMapExe = Executors.newFixedThreadPool(1);
future0 = CompletableFuture.runAsync(new orintMapRun(SysConsts.ORINT_DEG_ZERO , this.laplaceImgList), orintMapExe);
future1 = CompletableFuture.runAsync(new orintMapRun(SysConsts.ORINT_DEG_45 , this.laplaceImgList), orintMapExe);
future2 = CompletableFuture.runAsync(new orintMapRun(SysConsts.ORINT_DEG_90 , this.laplaceImgList), orintMapExe);
future2 = CompletableFuture.runAsync(new orintMapRun(SysConsts.ORINT_DEG_135 , this.laplaceImgList), orintMapExe);
CompletableFuture.allOf(future0,future1,future2,future3).join();//blocks the main …Run Code Online (Sandbox Code Playgroud) java multithreading executorservice countdownlatch threadpool
我正在开发一个API.此API需要执行2次DB查询才能获得结果.
我尝试了以下策略:
在Service中创建2个线程(使用Callable和CoundownLatch)并行运行2个查询并检测完成时间.
public class PetService {
public Object getData() {
CountDownLatch latch = new CountDownLatch(2);
AsyncQueryDBTask<Integer> firstQuery= new AsyncQueryDBTask<>(latch);
AsyncQueryDBTask<Integer> secondQuery= new AsyncQueryDBTask<>(latch);
latch.await();
}
public class AsyncQueryDBTask<T> implements Callable {
private CountDownLatch latch;
public AsyncQueryDBTask(CountDownLatch latch) { this.latch = latch;}
@Override
public T call() throws Exception {
//Run query
latch.countDown();
}
Run Code Online (Sandbox Code Playgroud)它工作正常,但我觉得我正在破坏Spring的结构.
我想知道在Spring 4中获取数据的最有效方法是什么.
- 如何知道运行自己查询的2个线程完成了他们的工作?
- 如何控制线程资源,如使用和释放线程?
提前致谢.
我创建了一个小型电影租赁模拟程序.以下是它的工作原理: - 主线程允许用户输入客户名称
所以这似乎工作得很好; 它适用于添加的前5个客户.在5号之后添加的客户似乎卡在semaphore.aquire()等待,我无法理解为什么,所以我在这里问.所有的帮助将非常赞赏:)
App.java:
import java.lang.System;import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class App {
public static CountDownLatch latch = new CountDownLatch(5);
public static Executor executor = Executors.newCachedThreadPool();
public static Store store = new Store();
public static Semaphore semaphore = new Semaphore(Store.getMovies().size());
Scanner in;
public App() {
in = new Scanner(System.in);
while (true) {
executor.execute(new Customer(in.nextLine()));
}
}
public static void main(String[] args) {
new App(); …Run Code Online (Sandbox Code Playgroud) 我有两个线程t1和t2.他们两个都进行了一些计算,我试着阻止主线程直到t1和t2完成.我使用.awaitTermination()如下所示,但问题是,despit它是一个if语句,.awaitTermination()进入无限循环.
请帮助我找到正在发生的事情.我应该在不知道t1和t2需要完成的确切时间的情况下指定一段时间吗?
executor.execute(new RunnableClass(bgr,3))
executor.execute(new RunnableClass(bgr,7))
executor.shutdown();
if (executor.awaitTermination(3, TimeUnit.SECONDS)) {
print("terminated")
}
Run Code Online (Sandbox Code Playgroud) 我们在java中有三种不同的多线程技术 - Fork/Join池,Executor Service和CountDownLatch
Fork/Join pool(http://www.javacodegeeks.com/2011/02/java-forkjoin-parallel-programming.html)
Fork/Join框架旨在使分而治之的算法易于并行化.这种类型的算法非常适合于可以分为两个或更多相同类型的子问题的问题.他们使用递归将问题分解为简单的任务,直到这些变得足够简单直接解决.然后组合子问题的解决方案以给出原始问题的解决方案
ExecutorService是一个扩展Executor类并表示异步执行的接口.它为我们提供了管理结束和检测异步任务进度的机制.
invokeAll():执行给定的任务,返回一个Futures列表,其中包含完成后的状态和结果.对于返回列表的每个元素,Future.isDone()都为true.
CountDownLatch :( http://examples.javacodegeeks.com/core-java/util/concurrent/countdownlatch-concurrent/java-util-concurrent-countdownlatch-example/)
CountDownLatch用于同步,以允许一个或多个线程等待,直到在其他线程中执行的一组操作完成.
我的假设:
在这两种替代方案中,只有在完成所有任务/线程后才能知道最终结果.
这三种选择是互补的还是互补的?
java multithreading executorservice countdownlatch forkjoinpool
我刚开始玩CountDownLatch我的Android应用程序.目前我正在尝试向Volley我的api 发出两个请求,并等待数据被检索并存储,然后再继续执行线程.
这是我的代码示例:
// new CountDownLatch for 2 requests
final CountDownLatch allDoneSignal = new CountDownLatch(2);
transactions.getResourcesForRealm(Contact.class, "", new ICallBack<Contact>() {
@Override
public void onSuccess(ArrayList<Contact> resources, String resourceId) {
transactions.createRealmObject(resources, Contact.class);
allDoneSignal.countDown();
}
@Override
public void onFail(ArrayList<Contact> resources) {
}
});
transactions.getResourcesForRealm(Meeting.class, "", new ICallBack<Meeting>() {
@Override
public void onSuccess(ArrayList<Meeting> resources, String resourceId) {
transactions.createRealmObject(resources, Meeting.class);
allDoneSignal.countDown();
}
@Override
public void onFail(ArrayList<Meeting> resources) {
}
});
try {
allDoneSignal.await();
// continue executing code
// ...
} catch …Run Code Online (Sandbox Code Playgroud) countdownlatch ×10
java ×10
semaphore ×2
android ×1
concurrency ×1
forkjoinpool ×1
nonblocking ×1
spring ×1
threadpool ×1