服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

java 线程入门――线程的同步


  //可以尝试把下面的关键字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();

}

}

扫描关注微信公众号