等到子线程完成:Java
发布时间:2020-12-14 16:22:54 所属栏目:Java 来源:网络整理
导读:问题描述 : – 步骤1:从主线程的用户输入FILE_NAME. 步骤2:对该文件执行10个操作(即计数字符,计数行等),所有这10个操作必须在隔离线程中.这意味着必须有10个子线程. 步骤3:主线程等待所有这些子线程完成. 步骤4:打印结果. 我做了什么 :- 我做了一个3线
问题描述 : –
步骤1:从主线程的用户输入FILE_NAME. 步骤2:对该文件执行10个操作(即计数字符,计数行等),所有这10个操作必须在隔离线程中.这意味着必须有10个子线程. 步骤3:主线程等待所有这些子线程完成. 步骤4:打印结果. 我做了什么 :- 我做了一个3线程的示例代码.我不想要你的文件操作代码. 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类也是一样的.但我不想使用该类. 我看了this similar solution,我只想使用Thread的方法. 解决方法
你可以做:
Thread t = new Thread() { public void run() { System.out.println("text"); // other complex code } }; t.start(); t.join(); 这样,您将等到线程完成,然后继续.你可以加入多个线程: for (Thread thread : threads) { thread.join(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- java – 在servlet中首先调用destroy()还是finalize()?
- 我可以暂时挂起SharePoint Server IIS SQL Server吗?
- java – 为什么`instanceof`错误而不是在用于2个不兼容的类
- Java通用问题
- java.lang.ClassNotFoundException: org.springframework.w
- java – 在int类型中设置4位半字节
- 将未实现的方法委托给Java中包含的对象的最短方法是什么?
- java – GWT EventBus中的大事件列表
- java – 在同一对象中测试方法时如何模拟对象中的方法
- 如何在java中使用apache math 3.0生成直方图的bin?