有这样的代码:class myThread extends Thread
{
Myobj obj;//这是一个线程安全的对象,比如Vector
public void run()
{
while(true)
{
if(obj.state=="ready")
{
process(obj);
obj.state="notready";
}
}
}
public void setready()
{
this.obj.state="ready";
}
}setready()方法由构造这个线程的代码调用.
现在我想让这个线程阻塞直到obj.state=="ready",处理后再次进入阻塞.应该怎么实现?
谢谢了~
{
Myobj obj;//这是一个线程安全的对象,比如Vector
public void run()
{
while(true)
{
if(obj.state=="ready")
{
process(obj);
obj.state="notready";
}
}
}
public void setready()
{
this.obj.state="ready";
}
}setready()方法由构造这个线程的代码调用.
现在我想让这个线程阻塞直到obj.state=="ready",处理后再次进入阻塞.应该怎么实现?
谢谢了~
if(!"ready".equals(obj.state)){
Thread.sleep(1000); // 我看你休眠比较好。
}else{
.... // 正常的操作
}
}
synchronized(obj){
if(!"ready".equals(obj.state)){
wait(); 这个要求对方同样用obj作为同步对象,并发出nodify.notifAll方法。
}else{
。//
}
}
}
public static final Myobj obj = ...; 作为同步的对象,方便程序操作。
import java.util.regex.*;
import java.util.*;
class Food{}class Table extends LinkedList{
int maxSize;
public Table(int maxSize){
this.maxSize = maxSize;
}
public synchronized void putFood(Food f){
while(this.size() >= this.maxSize){
try{
this.wait();
}catch(Exception e){}
}
this.add(f);
notifyAll();
}
public synchronized Food getFood(){
while(this.size() <= 0){
try{
this.wait();
}catch(Exception e){}
}
Food f = (Food)this.removeFirst();
notifyAll();
return f;
}
}
class Chef extends Thread{
Table t;
String name;
Random r = new Random(12345);
public Chef(String name,Table t){
this.t = t;
this.name = name;
}
public void run(){
while(true){
Food f = make();
System.out.println(name+" put a Food:"+f);
t.putFood(f);
}
}
private Food make(){
try{
Thread.sleep(200+r.nextInt(200));
}catch(Exception e){}
return new Food();
}
}class Eater extends Thread{
Table t;
String name;
Random r = new Random(54321);
public Eater(String name,Table t){
this.t = t;
this.name = name;
}
public void run(){
while(true){
Food f = t.getFood();
System.out.println(name+" get a Food:"+f);
eat(f);
}
}
private void eat(Food f){
try{
Thread.sleep(400+r.nextInt(200));
}catch(Exception e){}
}
}public class Test {
public static void main(String[] args) throws Exception{
Table t = new Table(10);
new Chef("Chef1",t).start();
new Chef("Chef2",t).start();
new Chef("Chef3",t).start();
new Chef("Chef4",t).start();
new Eater("Eater1",t).start();
new Eater("Eater2",t).start();
new Eater("Eater3",t).start();
new Eater("Eater4",t).start();
new Eater("Eater5",t).start();
new Eater("Eater6",t).start(); }
}