我想创建一个有两个线程的应用程序 一个线程读取字符数据 另一个线程将其打印到控制台 我有以下代码到 interThreadCommunication (假设文件有类似 s t a c k over e r f l o w 的数据) 我正在生成如下输出:
From echo int 115 char value s
From echo int 116 char value t
From echo int 97 char value a
From echo int 99 char value c
From echo int 107 char value k
From echo int 111 char value o
From echo int 118 char value v
From echo int 101 char value e
From echo int 114 char value r
From echo int 102 char value f
From echo int 108 char value l
From echo int 111 char value o
From echo int 119 char value w
From echo int 10 char value
代码:
import java.io.*;
class store
{
int i;
public int get()
{
return i;
}
public void set(int i)
{
this.i=i;
}
}
public class Main
{
public static void main(String a[])
{
store s=new store();
Thread th=new Thread(new read(s));
Thread pr=new Thread(new echo(s));
th.start();
pr.start();
}
}
class echo implements Runnable
{
store st;
public echo(store s)
{
st=s;
}
public void run()
{
while(true)
{
int t=st.get();
if(t==-1)
break;
if(t!=32)
{
System.out.println("From echo int "+t+" char value "+(char)st.get());
}
st.set(0);
try
{
//Thread.sleep(200);
while(true)
{
this.wait();
if(st.get()!=0)
break;
}
}
catch(Exception r)
{
}
}
}
}
class read implements Runnable
{
FileReader fr=null;
int r;
store st;
public read(store s)
{
st=s;
}
public void run()
{
try
{
fr=new FileReader("data.txt");
while(true)
{
int r=fr.read();
st.set(r);
while(st.get()==0)
{
this.wait();
}
if(r==-1)
break;
try
{
Thread.sleep(200);
}
catch(Exception re)
{
}
}
st.set(-1);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
fr.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
如果我从 read & echo
类中删除 sleep()
方法,那么我会得到
From echo int 0 char value
From echo int 0 char value
From echo int 0 char value
.
.
.
我正在使用wait()
方法让另一个线程可以处理。
我正在以正确的方式做,或者 interThreadCommunication
最佳答案
你应该考虑使用生产者-消费者模式:
线程 A 将从文件中读取条目,并将它们放入队列中。
线程 B 将从队列中读取条目并打印它们。
您可以使用 blocking queue implementation为了队列的线程安全。
我也会考虑不要将一个字符放入队列,但可能是一组字符(一个单词,或一行),
为了减少入队和出队的数量(因为这些方法是线程安全的,它们比非同步方法有更高的性能损失)。
关于java : Mutithreading & file reading,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13441198/