等待子线程完成:Java
问题描述:- 步骤1:从主线程的用户处获取输入文件名 步骤2:对该文件执行10个操作(即计数字符、计数行等),所有这10个操作必须在分隔线程中进行。这意味着必须有10个子线程 步骤3:主线程等待所有子线程完成 第四步:打印结果 我做了什么:- 我用3个线程编写了一个示例代码我不想从您这边得到文件操作代码。等待子线程完成:Java,java,multithreading,Java,Multithreading,问题描述:- 步骤1:从主线程的用户处获取输入文件名 步骤2:对该文件执行10个操作(即计数字符、计数行等),所有这10个操作必须在分隔线程中进行。这意味着必须有10个子线程 步骤3:主线程等待所有子线程完成 第四步:打印结果 我做了什么:- 我用3个线程编写了一个示例代码我不想从您这边得到文件操作代码。 public class ThreadTest { // This is object to synchronize on. private static final Obje
public class ThreadTest {
// This is object to synchronize on.
private static final Object waitObject = ThreadTest.class;
// Your boolean.
private static boolean boolValue = false;
public final Result result = new Result();
public static void main(String[] args) {
final ThreadTest mytest = new ThreadTest();
System.out.println("main started");
new Thread(new Runnable() {
public void run() {
System.out.println("Inside thread");
//Int initialiser
new Thread(new Runnable() {
public void run() {
System.out.println("Setting integer value");
mytest.result.setIntValue(346635);
System.out.println("Integer value seted");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
//String initialiser
new Thread(new Runnable() {
public void run() {
System.out.println("Setting string value");
mytest.result.setStringValue("Hello hi");
System.out.println("String value seted");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
//Boolean initialiser
new Thread(new Runnable() {
public void run() {
System.out.println("Setting boolean value");
mytest.result.setBoolValue(true);
System.out.println("Boolean value seted");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
System.out.println("Thread is finished");
//Notify to main thread
synchronized (ThreadTest.waitObject) {
ThreadTest.boolValue = true;
ThreadTest.waitObject.notifyAll();
}
}
}).start();
try {
synchronized (ThreadTest.waitObject) {
while (!ThreadTest.boolValue) {
ThreadTest.waitObject.wait();
}
}
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.println("main finished");
System.out.println("Result is : " + mytest.result.toString());
}
}
问题:-
我上面的代码没有给出正确答案。我该怎么做
替代解决方案:
CountDownLatch类也执行相同的操作。但我不想使用那个类
我看了,我只想使用线程的方法 您可以执行以下操作:
Thread t = new Thread() {
public void run() {
System.out.println("text");
// other complex code
}
};
t.start();
t.join();
这样,您将等待线程完成,然后继续。您可以连接多个线程:
for (Thread thread : threads) {
thread.join();
}
我建议先看一下框架,然后再看一下框架
然后你可以这样写:
ExecutorService executor = Executors.newFixedThreadPool(maxThreadsToUse);
CompletionService completion = new ExecutorCompletionService(executor);
for (each sub task) {
completion.submit(new SomeTaskYouCreate())
}
// wait for all tasks to complete.
for (int i = 0; i < numberOfSubTasks; ++i) {
completion.take(); // will block until the next sub task has completed.
}
executor.shutdown();
ExecutorService executor=Executors.newFixedThreadPool(maxThreadsToUse);
CompletionService completion=新执行人CompletionService(执行人);
对于(每个子任务){
完成。提交(新建SomeTaskYouCreate())
}
//等待所有任务完成。
for(int i=0;i
有很多方法可以做到这一点。考虑倒计时锁:
import java.util.concurrent.CountDownLatch;
public class WorkerTest {
final int NUM_JOBS = 3;
final CountDownLatch countDownLatch = new CountDownLatch(NUM_JOBS);
final Object mutex = new Object();
int workData = 0;
public static void main(String[] args) throws Exception {
WorkerTest workerTest = new WorkerTest();
workerTest.go();
workerTest.awaitAndReportData();
}
private void go() {
for (int i = 0; i < NUM_JOBS; i++) {
final int fI = i;
Thread t = new Thread() {
public void run() {
synchronized(mutex) {
workData++;
}
try {
Thread.sleep(fI * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
}
};
t.start();
}
}
private void awaitAndReportData() throws InterruptedException {
countDownLatch.await();
synchronized(mutex) {
System.out.println("All workers done. workData=" + workData);
}
}
}
import java.util.concurrent.CountDownLatch;
公共班工人测验{
最终int NUM_作业=3;
最终CountDownLatch CountDownLatch=新的CountDownLatch(NUM_作业);
最终对象互斥体=新对象();
int workData=0;
公共静态void main(字符串[]args)引发异常{
WorkerTest WorkerTest=新WorkerTest();
workerTest.go();
workerTest.awaitAndReportData();
}
私人空间{
对于(int i=0;i
您可以从java.util.concurrent
中进行选择。来自JavaDocs:
一种同步辅助工具,允许一个或多个线程等待
在其他线程中执行的一组操作完成
示例代码:
import java.util.concurrent.CountDownLatch;
public class Test {
private final ChildThread[] children;
private final CountDownLatch latch;
public Test() {
this.children = new ChildThread[4];
this.latch = new CountDownLatch(children.length);
children[0] = new ChildThread(latch, "Task 1");
children[1] = new ChildThread(latch, "Task 2");
children[2] = new ChildThread(latch, "Task 3");
children[3] = new ChildThread(latch, "Task 4");
}
public void run() {
startChildThreads();
waitForChildThreadsToComplete();
}
private void startChildThreads() {
Thread[] threads = new Thread[children.length];
for (int i = 0; i < threads.length; i++) {
ChildThread child = children[i];
threads[i] = new Thread(child);
threads[i].start();
}
}
private void waitForChildThreadsToComplete() {
try {
latch.await();
System.out.println("All child threads have completed.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class ChildThread implements Runnable {
private final String name;
private final CountDownLatch latch;
protected ChildThread(CountDownLatch latch, String name) {
this.latch = latch;
this.name = name;
}
@Override
public void run() {
try {
// Implementation
System.out.println(name + " has completed.");
} finally {
latch.countDown();
}
}
}
public static void main(String[] args) {
Test test = new Test();
test.run();
}
}
import java.util.concurrent.CountDownLatch;
公开课考试{
私人最终子女线程[]子女;
私有最终倒计时闩锁;
公开考试(){
this.children=新的子线程[4];
this.lack=新的倒计时闩锁(childrence.length);
子线程[0]=新的子线程(闩锁,“任务1”);
子线程[1]=新的子线程(闩锁,“任务2”);
子线程[2]=新的子线程(闩锁,“任务3”);
子线程[3]=新的子线程(闩锁,“任务4”);
}
公开募捐{
startChildThreads();
waitForChildThreadsToComplete();
}
私有void startChildThreads(){
线程[]线程=新线程[children.length];
对于(int i=0;i
输出:
任务1已完成。
任务4已完成。
任务3已完成。
任务2已完成。
所有子线程都已完成。在Java 8中,更好的方法是使用parallelStream()
注意:更容易准确地看到这些后台任务在做什么
public static void main(String[] args) {
Stream.<Runnable>of(
() -> mytest.result.setIntValue(346635),
() -> mytest.result.setStringValue("Hello hi"),
() -> mytest.result.setBoolValue(true) )
.parallel()
.forEach(Runnable::run);
System.out.println("main finished");
System.out.println("Result is : " + mytest.result.toString());
}
publicstaticvoidmain(字符串[]args){
溪流(
()->mytest.result.setIntValue(346635),
()->mytest.result.setString值(“你好”),
()->mytest.result.setBoolValue(true))
.parallel()
.forEach(Runnable::run);
系统输出打印项次(“主成品”);
System.out.println(“结果是:+mytest.Result.toString());
}
我取出了调试信息和睡眠,因为它们不会改变结果。每n秒检查一次是否所有子线程都已死亡。简单而有效的方法:
boolean allDead=false;
while(! allDead){
allDead=true;
for (int t = 0; t < threadCount; t++)
if(threads[t].isAlive()) allDead=false;
Thread.sleep(2000);
}
boolean allDead=false;
当(!都死了){
全死=真;
对于(int t=0;t