2 つのスレッドがあるアプリケーションを作成したい 1 つのスレッドが char データを読み取り、別のスレッドがそれをコンソールに出力します。
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の別の方法があります