下面程序是两个线程,自己编的,分别放球,取球,我想用到wait()和notify()不知道怎么加,达到,放个红球取红球,然后放蓝球,取蓝球,再放红球取红球,放10次。求会的花点时间讲解下,再此先谢了。
class Ball{
private String color;
private int size;
Boolean flag=true;
public void setColor(String color){
this.color=color;
}
public void setSize(int size){
this.size=size;
}
public String getColor(){
return color;
}
public int getSize(){
return size;
}
}
class putBall implements Runnable{
Ball ball=new Ball();
public putBall(Ball ball){
this.ball=ball;
}
public void run(){
for(int i=0;i<10;i++){
synchronized (this) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(ball.flag){
ball.setColor("red");
ball.setSize(5);
}else
{
ball.setColor("blue");
ball.setSize(10);
}
}
}
}
}
class getBall implements Runnable{
Ball ball=new Ball();
public getBall(Ball ball){
this.ball=ball;
}
public void run(){
for(int i=0;i<10;i++){
synchronized (this) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("颜色:"+ball.getColor()+",大小:"+ball.getSize());
ball.flag=!ball.flag;
}
}
}
}
public class hui{
public static void main(String args[]){
Ball b=new Ball();
Thread t1=new Thread(new putBall(b));
Thread t2=new Thread(new getBall(b));
t1.start();
t2.start();
}
}
多线程 wait() notify()
------解决方案--------------------
我修改了一下,楼主参考一下:
class Ball {
private String color;
private int size;
private boolean flag = true;//用boolean 即可。