/**
* 打印工作类
* @author Administrator
*
*/
public class Job implements Runnable {
private PrintQueue printQueue;
public Job(PrintQueue printQueue) {
super();
this.printQueue = printQueue;
}
@Override
public void run() {
printQueue.printJob(new Object());
}
/**
* 主函数入口
* 创建了10个线程
* @param args
*/
public static void main(String[] args) {
PrintQueue pq = new PrintQueue();
Thread thread[] = new Thread[10];
for (int i = 0; i < 10; i++) {
thread[i] = new Thread(new Job(pq), "Thread"+i);
}
for (int i = 0; i < 10; i++) {
thread[i].start();
}
}
}
/**
* 打印队列
* @author Administrator
*
*/
public class PrintQueue {
private final Lock queueLock = new ReentrantLock();
//打印工作
public void printJob(Object document) {
//获取控制权
queueLock.lock();
long duration = (long) (Math.random() * 10000);
System.out.println(Thread.currentThread().getName()+":Test print job ! "+duration);
try {
Thread.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
//如果不释放锁,会造成死锁现象
queueLock.unlock();
}
}
}