Professional Documents
Culture Documents
Sync Demo5
Sync Demo5
Random;
class buff_zone {
}
public class sync_lock implements Runnable{
@Override
public void run() {
int thread_id =
Integer.parseInt(Thread.currentThread().getName().substring(7));
if (thread_id >= num) {
synchronized (empty) {
while (buff_zone.isEmpty()) { System.out.print(""); }
synchronized (mutex) {
System.out.println("线程" + thread_id + ":这是一个消费者线程");
System.out.println("线程" + thread_id + ":进入缓冲区");
try{ Thread.sleep(300); } catch (InterruptedException e) {
e.printStackTrace(); }
buff_zone.consume();
System.out.println("线程" + thread_id + ":退出缓冲区");
System.out.println();
}
}
} else {
synchronized (full) {
while (buff_zone.isFull()) { System.out.print(""); }
synchronized (mutex) {
System.out.println("线程" + thread_id + ":这是一个生产者线程");
System.out.println("线程" + thread_id + ":进入缓冲区");
try{ Thread.sleep(300); } catch (InterruptedException e) {
e.printStackTrace(); }
buff_zone.produce();
System.out.println("线程" + thread_id + ":退出缓冲区");
System.out.println();
}
}
}
}
}