我想创建有两个线程的应用程序一个线程读取字符数据另一个线程将其打印到控制台我有以下代码到 interThreadCommunication(假设文件具有类似 stackoverflow 的数据)我正在生成如下输出:
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();
}
}
}
}
如果我sleep()
从两个类中删除方法,read & echo
那么我会得到
From echo int 0 char value
From echo int 0 char value
From echo int 0 char value
.
.
.
我正在使用wait()
另一个线程可以处理的方法。我正在以正确的方式进行操作,或者还有其他用于interThreadCommunication的方法