【问题标题】:Why just one of 5 threads pop elements from stack?为什么只有 5 个线程之一从堆栈中弹出元素?
【发布时间】:2020-08-16 20:56:19
【问题描述】:
public class ClassTest extends Thread{

    public static Object lock = new Object();
    
    public static LinkedList<Integer> stack;
    public SortedSet<Integer> set= new TreeSet<>();
    @Override
        public void run(){
            
            synchronized(lock){
                // try{
                    // this.wait();
                // }
                // catch(Exception e){
                    // e.printStackTrace();
                // }
                
                
                while(!stack.isEmpty()){
                    set.add(stack.pop());
                    
                    this.yield();
                    
                    // this.notifyAll();
                    
                }
                
                
            }
            
            
        }

当我开始()5个线程时,为什么只有第一个弹出所有元素而其他人不弹出任何人? 我尝试使用 wait() 和 notify() 方法,但没有帮助..

【问题讨论】:

    标签: java multithreading synchronization thread-safety


    【解决方案1】:

    yield 方法不会释放锁。进入同步块的第一个线程将阻止其他线程进入,直到堆栈为空并释放锁。


    这是一个使用LinkedBlockingDeque 做你想做的事的例子。

    import java.util.HashSet;
    import java.util.Set;
    import java.util.concurrent.LinkedBlockingDeque;
    
    
    class Main {
        
        static final LinkedBlockingDeque<Integer> stack = new LinkedBlockingDeque<>();
        
        
        static class Poller implements Runnable {
            final Set<Integer> set = new HashSet<>();
            
            @Override
            public void run() {
                Integer elem = stack.poll();
                while (elem != null) {
                    set.add(elem);
                    System.out.printf("%s: %d\n", Thread.currentThread().getName(), elem);
                    elem = stack.poll();
                }
            }
        }
        
        
        public static void main(String args[]) {
            for (int i = 0; i < 100; i++) {
                stack.push(i);
            }
            for (int i = 0; i < 5; i++) {
                new Thread(new Poller()).start();
            }
        }
    }
    

    【讨论】:

    • 哦,是的,你是对的.. 谢谢.. 那么,你建议做什么,也许是其他方式?
    • @DevJava 首先,我建议接受答案,因为这是您问题的答案。 ;-) 然后我建议不要在这里使用synchronized。您可以使用在方法上同步的数据结构,例如LinkedBlockingDeque。然后所有线程都可以在它上面调用poll,只要poll 不返回null。请注意,您还需要为set 使用同步数据结构。
    • 感谢您的回答.. 很抱歉打扰您,但是有什么方法可以使用同步块(可能使用 wait() 和 notify() 方法,或者不可能.. 谢谢再次..
    • @DevJava 我刚刚添加了一个带有LinkedBlockingDeque 的示例。这并不像你想象的那么难。是的,有一种方法可以使用waitnotify,但它基本上是围绕堆栈上的每个访问实现synchronized。你懂我的意思吗?在这里使用wait/notify真的没有意义。
    猜你喜欢
    • 2022-01-21
    • 2018-05-02
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    相关资源
    最近更新 更多