大家先看我的测试程序:
public class Test{
public static void main( String[] args ){
final Pool pp = new Pool();
new Thread(){ //启动线程1
public void run(){
System.out.println(" before allotTable()方法");
pp.allotTable( this );
System.out.println(" after allotTable()方法");
}
}.start();
new Thread(){ //启动线程2
public void run(){
try {
sleep(1000);
} catch (InterruptedException e) { }
System.out.println( "线程2=="+pp.clq.poll() );
}
}.start();
}
}
class Pool {
ConcurrentLinkedQueue clq = new ConcurrentLinkedQueue();
public synchronized void allotTable( Thread t ){
System.out.println("add");
clq.add( "aa" );
clq.add( "bb" );
clq.add( "cc" );
System.out.println("added");
try {
t.sleep( 10000 );
//this.wait( 10000 );
} catch (InterruptedException e) {}
System.out.println( clq.poll() );
System.out.println( clq.poll() );
System.out.println( clq.poll() );
}
}
我的想法是这样的,Pool的allotTable()方法先是在ConcurrentLinkedQueue中添加了三个元素,然后sleep,或者wait一定时间,再打印
而主方法中是先启动线程1,执行allotTable()方法,那么他再方法里面肯定会sleep或者wait.
如果是第一种情况sleep的,由于API上说ConcurrentLinkedQueue是线程安全的,在一个同步的方法里面,sleep是又是不会释放锁的,
当启动线程2去取里面的元素的时候,应该是取不到的(考虑到线程的优先级线程2也sleep一秒,保证allotTable()先执行添加元素)
可我的结果是可以取到,而且还不是很稳定,多运行几次也有取不到的时候. ???????
如果是第二中情况wait的,因为他是会释放锁的,所以是可以取到的.
我看了ConcurrentLinkedQueue的源码,看的不是很懂,也搞不清他是怎样保证线程安全的,他的方法没有一个是Synchronized的,而Vector也是线程安全的,他的方法全是Synchronized的
我是新手可能考虑的不是很全面,请各位高手前辈帮忙看看,或者一起讨论一下.