日期:2014-05-20 浏览次数:20768 次
package slot;
public class ThreadPriority {
/**
* @param args
*/
public static void main(String[] args) {
Slot s = new Slot();
// TODO Auto-generated method stub
for(int i=1; i<6 ;i++)
{
Consumer cr = new Consumer(s) ;
cr.setPriority(i);
cr.start();
}
Producer p = new Producer(s);
p.start();
}
}
class Slot {
public int slotNum = 0;
public synchronized void produce() {
slotNum++;
}
public synchronized void consume() {
slotNum--;
}
}
class Producer extends Thread {
Slot slot;
public Producer(Slot s) {
slot = s;
}
public void run() {
try {
synchronized (slot) {
while (slot.slotNum == 20)
slot.wait();
slot.produce();
slot.notifyAll();
System.out.println("Thread " + this.getName() + " producing ! slotNum is " + slot.slotNum+"\n");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Consumer extends Thread {
Slot slot;
public Consumer(Slot s) {
slot = s;
}
public void run() {
try {
synchronized (slot) {
while (slot.slotNum == 0)
slot.wait();
slot.consume();
slot.notifyAll();
System.out.println(" -------------- Thread " + this.getName() + " consuming ! slotNum is " + slot.slotNum+"\n");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}