我试图找出 java 中的线程,并试图理解我得到的输出。我创建了 3 个类:发送者、接收者和消息框。
我正在尝试通过消息框将数据从发送者发送到接收者。当发送方发送数据时,它会打印“发送方放置元素”。一旦接收者获得一个元素,它就会打印“接收者获得元素”
问题是,在控制台中,我看到接收者打印出他在发送者打印出他发送了该元素之前获得了该元素。
发件人:
public class Sender implements Runnable {
private MessageBox msgBox;
public Sender(MessageBox m)
{
msgBox=m;
}
public void run()
{
Thread.currentThread().setName("Sender");
for(int i=0;i< 100;i++)
{
msgBox.put(i);
System.out.println("Sender put element : " + i);
try {
long sleep_time = (long)(Math.random()*5000);
//System.out.println("Sender going to sleep for " + sleep_time + " ms");
Thread.sleep(sleep_time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
接收者 :
public class Receiver implements Runnable{
private MessageBox<Integer> msgBox;
public Receiver(MessageBox<Integer>m)
{
msgBox = m;
}
public void run()
{
Thread.currentThread().setName("Receiver");
while(true)
{
int element = msgBox.get();
System.out.println("Receiver got element : " + element);
try
{
long sleep_time = (long)(Math.random()*5000);
//System.out.println("Receiver going to sleep for " + sleep_time + " ms");
Thread.sleep(sleep_time);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
莫回无
智慧大石
相关分类