修改 我有一个生产者类,它将一些数据发送到SharedBuffer类。此数据被添加到ArrayList,其限制设置为100.向所述列表添加数据没有问题,但是使用者类无法从列表中获取任何数据。
根本没有产生任何输出(没有空或错误)。
编辑2:添加了将数据放入数组的方法。
SharedBuffer类:
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Opacity = 0.5;
this.TopMost = true;
}
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
const int GWL_EXSTYLE = -20;
const int WS_EX_LAYERED = 0x80000;
const int WS_EX_TRANSPARENT = 0x20;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
var style = GetWindowLong(this.Handle, GWL_EXSTYLE);
SetWindowLong(this.Handle,GWL_EXSTYLE , style | WS_EX_LAYERED | WS_EX_TRANSPARENT);
}
}
消费者类:
static final int RESOURCE_LIMIT = 100;
private List<String> data = new ArrayList<String>();
// private boolean done = false;
public boolean isFull(){
return data.size() >= RESOURCE_LIMIT;
}
public boolean isEmpty(){
return data.size() <= 0;
}
public synchronized void putData(String s){
while(this.isFull()){
try{
wait();
}catch(InterruptedException e){
//
e.printStackTrace();
}
}
data.add(s);
//size works and there is data in list.
//System.out.println(data.size() + data.get(0));
public boolean isEmpty(){
return data.size() <= 0;
}
public synchronized String getData(){
while(this.isEmpty()){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
String s_data = (String)(data.get(0));
if(s_data != null){
data.remove(s_data);
System.out.println(s_data);
}
return s_data;
}
答案 0 :(得分:1)
更改您的代码(添加notyfyAll()
invokation)
public synchronized void putData(String s){
while(this.isFull()){
try{
wait();
}catch(InterruptedException e){
//
e.printStackTrace();
}
}
data.add(s);
notifyAll();
}
public synchronized String getData(){
while(this.isEmpty()){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
String s_data = (String)(data.get(0));
if(s_data != null){
data.remove(s_data);
System.out.println(s_data);
}
notifyAll();
return s_data;
}
此外,您应该同步isEmpty
和isFull
方法,因为访问data
。