欢迎光临
我们一直在努力

Java 线程入门——线程的同步-JSP教程,Java技巧及代码

建站超值云服务器,限时71元/月

//可以尝试把下面的关键字synchronized去掉。

public class cubbyhole {

private int contents;

private boolean available = false;

public synchronized int get() {

while (available == false) {

try {

wait();

} catch (interruptedexception e) {

}

}

available = false;

notifyall();

return contents;

}

public synchronized void put(int value) {

while (available == true) {

try {

wait();

} catch (interruptedexception e) {

}

}

contents = value;

available = true;

notifyall();

}

}

public class producer extends thread {

private cubbyhole cubbyhole;

private int number;

public producer(cubbyhole c, int number) {

cubbyhole = c;

this.number = number;

}

public void run() {

for (int i = 0; i < 10; i++) {

cubbyhole.put(i);

system.out.println("producer #" + this.number + " put: " + i);

try {

sleep((int) (math.random() * 100));

} catch (interruptedexception e) {

}

}

}

}

public class consumer extends thread {

private cubbyhole cubbyhole;

private int number;

public consumer(cubbyhole c, int number) {

cubbyhole = c;

this.number = number;

}

public void run() {

int value = 0;

for (int i = 0; i < 10; i++) {

value = cubbyhole.get();

system.out.println("consumer #" + this.number + " got: " + value);

}

}

}

public class producerconsumertest {

public static void main(string[] args) {

cubbyhole c = new cubbyhole();

producer p1 = new producer(c, 1);

consumer c1 = new consumer(c, 1);

p1.start();

c1.start();

}

}

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » Java 线程入门——线程的同步-JSP教程,Java技巧及代码
分享到: 更多 (0)

相关推荐

  • 暂无文章