为什么只有5个线程之一从堆栈中弹出元素?

问题描述

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();
                    
                }
                
                
            }
            
            
        }

当我start()5个线程时,为什么只有第一个弹出所有元素,而其他却没有弹出任何人? 我尝试使用wait()和notify()方法,但这无济于事。

解决方法

方法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();
        }
    }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...