本帖最后由 唐长智 于 2013-3-4 21:12 编辑
为什么不能得到张老师视频中的结果呢?- import java.util.Random;import java.util.concurrent.Executors;
- import java.util.concurrent.locks.ReentrantReadWriteLock;
- public class ReaderWriterTest {
- public static void main(String[] args){
- final Queue q = new Queue();
- Executors.newFixedThreadPool(3).execute(new Runnable(){
- //创建线程池定义3个线程
- public void run(){
- while(true)
- {
- q.get();
- }
- }
- });
-
- for(int i = 0;i<3;i++){
- //创建3个线程
- new Thread(){
- public void run(){
- while(true){
- q.put(new Random().nextInt(1000));
- }
- }
- }.start();
- }
- }
- }
- class Queue{
- private Object data = null;
- //定义私有的data数据
- private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
- //定义私有的读写锁
- public void put(Object data){
- rwl.writeLock().lock();
- //使用写锁
- try {
- //打印put方法运行的当前线程和状态
- System.out.println(Thread.currentThread().getName() + "ready to write");
- Thread.sleep(1000);
- this.data = data;
- System.out.println(Thread.currentThread().getName() + "has write" + data);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- finally{
- rwl.writeLock().unlock();
- //释放写锁
- }
-
- }
-
- public void get(){
- rwl.readLock().lock();
- //使用读锁
- try {
- //打印get方法运行的当前线程和状态
- System.out.println(Thread.currentThread().getName() + "ready to read");
- Thread.sleep(1000);
- System.out.println(Thread.currentThread().getName() + "has read" + data);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- finally{
- rwl.readLock().unlock();
- //释放读锁
- }
- }
- }
复制代码 线程池中创建了3个线程来读取,为什么运行结果中只有一个线程在运行呢?
|