62,621
社区成员
发帖
与我相关
我的任务
分享
class Ball {
private String color;
private int size;
private boolean flag = true;//用boolean 即可。
//加上 set get方法。
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
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,等待外面传入。
public putBall(Ball ball) {
this.ball = ball;
}
public void run() {
for (int i = 0; i < 10; i++) {
//等待一般不要放在同步代码块里。
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (ball) {//用ball,this 不行。
while (!ball.isFlag()) {//false 有球,不可以放。
try
{
ball.wait();//这就用同步对象 ball的wait方法,等待取走球后才能放入。
} //而且要放在try catch块里,捕获异常。
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}//end while
//一旦从while退出来,说明球已经取走,可以放入了。
if(i % 2 ==0 ){//交替放球,偶数时放红球
ball.setColor("red");
ball.setSize(5);
}
else
{
ball.setColor("blue");//奇数时兰球
ball.setSize(10);
}
//一定要有这两句。
ball.setFlag(false);//改变标记
ball.notify();//唤醒等待的线程。
}//end synch.
}//end for.
}//end run
}//end class.
class getBall implements Runnable {
Ball ball;
public getBall(Ball ball) {
this.ball = ball;
}
public void run() {
for (int i = 0; i < 10; i++) {
//等待一般不要放在同步代码块里。
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (ball) {//用ball对象做同步对象,this没有用。
while(ball.isFlag()){//ture 没有球,需要等待。
try{
ball.wait();
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}//end while
//一旦退出了while,就是已经放入球了,可以取。
System.out.println("颜色:" + ball.getColor() + ",大小:"
+ ball.getSize());
//加这两句,改标志,唤醒。
ball.setFlag(true);
ball.notify();
}//end synch
}//end for
}//end run
}//end class
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();
}
}
结果:
颜色:red,大小:5
颜色:blue,大小:10
颜色:red,大小:5
颜色:blue,大小:10
颜色:red,大小:5
颜色:blue,大小:10
颜色:red,大小:5
颜色:blue,大小:10
颜色:red,大小:5
颜色:blue,大小:10
