我有一个的FileReader类,这是这样的Java的等待两个线程通知作为同一类
public class FileReader extends Thread
{
private final Object lock = new Object();
public FileReader(String path, FileReaderCallback callback)
{
super(path);
this.path = path;
this.callback = callback;
}
@Override
public void run()
{
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
String info;
while ((info = reader.readLine()) != null)
{
synchronized (lock)
{
callback.onDone(path, info);
try
{
lock.wait();
}
catch (Exception ignored)
{
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void next()
{
synchronized (lock)
{
try
{
lock.notify();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
而且我有这个的FileReader两个实例,因为我想同时读取线两种文件一行。问题是我的代码只从这两个文件中读取一行,然后它会暂停。
我所说的功能在我的回调这样
public void onDone(String path, String info)
{
reader1.next();
reader2.next();
}
那么,有什么问题?
在此先感谢
你的锁在哪里?你如何获得它们?请包括你所有的课程。 – ram
@ram我编辑了我的文章。我的锁在FileReader类中,但onDone函数在其他地方(在我的主类中) – strings95
'lock.wait()'你的运行代码在该行,并且你永远不会显示你在哪里调用next()' – nachokk