主线程wait等待子线程返回对象信息
2017-07-04 13:47
399 查看
需求:假设一个线程(JarThread)正在从网络连接(用System.in模拟)中读取一个JAR归档文件。这个归档文件中第一项是清单文件(用‘/’标识结束)。另一个线程(MainThread)可能对这个清单文件的内容感兴趣,即使归档文件的其余部分尚不可用。对清单文件感兴趣的线程会创建一个定制的ManifestFile对象,将这个对象的引用传递给将要读取JAR归档文件的线程,并等待这个对象。读取归档文件的线程首先用流中的项填写ManifestFile,然后通知ManifestFile,再继续读取JAR归档文件的其余部分。当阅读器线程通知ManifestFile时,原来的线程会被唤醒,按其计划处理现在已经完全准备就绪的ManifestFile对象
1. JarThread
public class JarThread implements Runnable { Logger logger = LoggerFactory.getLogger(JarThread.class); ManifestFile manifestFile; InputStream in; public JarThread(ManifestFile m, InputStream in) { this.manifestFile = m; this.in = in; } @Override public void run() { int i; //与MainThread获取同一个对象锁 synchronized (manifestFile) { //从流in中读入清单文件 try { while ((i = in.read()) != -1) { //如果字符/ 标志MainThread感兴趣的内容结束 if(i==47){ break; } manifestFile.add(i); } } catch (IOException e) { e.printStackTrace(); } //释放对象锁 manifestFile.notifyAll(); } //读取流的其他部分 try { while ((i = in.read()) != -1) { logger.info(String.valueOf((char)i)); } } catch (IOException e) { e.printStackTrace(); } } }
2. ManifestFile
public class ManifestFile { private StringBuffer content = new StringBuffer(); public synchronized StringBuffer getContent() { return content; } public synchronized void add(int i) { content.append((char)(i)); } }
3. MainThread
public class MainThread { final static Logger logger = LoggerFactory.getLogger(MainThread.class); public static void main(String[] args) throws IOException { InputStream in = System.in; //system.in如何判断读到了 ManifestFile m = new ManifestFile(); //启动读取线程 这里的需求比较特别 //并不是从线程中返回 而是返回所需要的部分,而线程继续执行 JarThread t = new JarThread(m, in); ExecutorService exec = Executors.newCachedThreadPool(); //首先获取对象锁 synchronized (m) { exec.execute(t); try { //挂起 释放锁 等待JarThread通知 m.wait(); //处理清单文件 logger.info(m.getContent().toString()); } catch (InterruptedException e) { e.printStackTrace(); } } } }
4. 执行结果
相关文章推荐
- 子线程返回前,使循环暂停但不使主线程卡死的办法,等待子线程有返回了之后,才执行主线程下一步代码的方法
- 线程-主线程等待子线程
- Java 线程 Thread 对象锁的wait和notify解析
- 查询锁等待的时间,被锁对象,SID等信息语句(参考OEM);
- 异步回调 主线程等待子线程结束
- 线程通信(子线程运行10次,主线程运行100次,如此循环50次)[用condition替代wait,notify等待和唤醒操作]
- 等待多于64(MAXIMUM_WAIT_OBJECTS)个线程
- 【Demo 0095】等待线程对象以及消息
- 非UI的子线程再启动线程的话,等待的时候会被阻塞,Task不会阻塞了
- 【摘录】正确理解线程等待和释放(wait/notify)
- java 线程wait()与notify()的用法(被唤醒后的线程到底重新执行同步代码块还是从那是等待的那里继续执行)
- Java 线程 Thread 对象锁的wait和notify解析
- WaitForSingleObject 等待线程句柄
- 重载toString方法,返回对象的详细信息
- 正确理解线程等待和释放(wait/notify)
- java线程等待、设置优先级、同步、挂起、恢复(Join、setPriority、synchronized、wait、notify……)
- 对话框中WaitForSingleObject等待线程退出导致程序阻塞的原因及解决
- 对话框中WaitForSingleObject等待线程退出导致程序阻塞的原因及解决
- 理解线程的等待释放(wait/notify)
- [多线程] WaitHandle.WaitAll ManualResetEvent 等待所有线程完成