我有一个Thread和一个Swingworker。 Swingworker从Thread获取值并在JPanel中发布它们。
由于我不希望线程继续直到Swingworker取值,我在无限循环中停止它,但是当我更改布尔值时,线程不会继续。
这是问题的一个例子:
Swingworker Class
public class Worker extends SwingWorker<Void,int>
{
Mail m;
MyJPanel jp;
public Worker(Mail m, MyJPanel jp)
{
this.m = m;
this.jp = jp;
}
protected Void doInBackground() throws Exception
{
int letter;
while(!m.getEnd())
{
letter = m.getMail();
publish(letter);
Thread.sleep(2000);
}
return null;
}
protected void process(List<int> chunks)
{
for (int number : chunks)
{
jp.setTextArea("Letter n " + number + " arrived");
}
}
}
邮件类
public class Mail extends Thread
{
private int delivery;
private int num;
private boolean stop = true;
private boolean end = false;
public Mail(int num)
{
this.num = num;
}
public void run()
{
for(int i = 0; i < num;i++)
{
doDelivery(i);
}
end = true;
}
public void doDelivery(int x)
{
delivery = x;
System.out.println("Delivery awaits");
while(stop);
System.out.println("Delivery completed");
stop = true;
}
public int getMail()
{
System.out.println("Taking the mail");
stop = false;
return delivery;
}
public boolean getEnd()
{
return end;
}
线程启动的部分代码
// being "panel" an extension of JPanel
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("start"))
{
int num = panel.getNum();
Mail m = new Mail(num);
Worker worker = new Worker(m,panel);
m.start();
worker.execute();
}
}
控制台中的输出为:
Delivery awaits
Taking the mail
//Span of 2 seconds
Taking the mail
Taking the mail
在textArea中是
Letter n 0 arrived
Letter n 0 arrived
Letter n 0 arrived
我从未看到“交付已完成”,因此即使Swingworker正在更改循环布尔值,线程也不会离开它。为什么呢?
答案 0 :(得分:0)
我用信号量替换了bool值,现在Mail类看起来像这样。
public class Mail extends Thread
{
private int delivery;
private int num;
private Semaphore sem = new Semaphore(0,true);
private boolean end = false;
public Mail(int num)
{
this.num = num;
}
public void run()
{
for(int i = 0; i < num;i++)
{
doDelivery(i);
}
end = true;
}
public void doDelivery(int x)
{
delivery = x;
System.out.println("Delivery awaits");
try {
sem.acquire();
} catch (InterruptedException ex) {};
System.out.println("Delivery completed");
}
public int getMail()
{
System.out.println("Taking the mail");
sem.release();
return delivery;
}
public boolean getEnd()
{
return end;
}
这似乎有效,但如果没有,我会更新。