线程中的方法和锁问题

method and lock issue in thread

这是我的线程代码

Thread decode = new Thread(new Runnable() {
        @Override
        public void run() {
            // System.out.println("decode thread started");
            synchronized (queueLock) {
                while (true) {
                    if (!queue.isEmpty()) {
                        System.out.println(decoding());
                    }
                }
            }
        }
    });

这是我的会员字段

private PriorityQueue<String> queue = new PriorityQueue<String>();
private Object queueLock = new Object();

这是我的方法

public Character decoding() {
    String code = queue.poll();     
    Character chr;
    Character[][] key = kG.getKey();
    String binary = null;
    Character startingCharacter = code.charAt(0);
    int iK = 0;
    int ascii;

    //System.out.println(code); when i use this other threads do not start also

    for (int i = 0; i < KeyGenerator.getIr(); i++)
        if (startingCharacter == key[i][0])
            iK = i;

    for (int j = 0; j < KeyGenerator.getJr(); j++) {
        if (code.contains(String.valueOf(key[iK][j])))
            binary = binary + "1";
        else
            binary = binary + "0";
    }

    ascii = Integer.parseInt(binary, 2);
    chr = (char) (ascii + 'a');

    return chr;
}

另一个线程正在使用 prioritqueue,但我使用 queueLock object 使其同步。 decoding 方法在 docode thread 中不起作用!!!

我认为您可以删除 queueLock 对象并锁定队列本身。

您当前构建代码的方式永远不会发布监视器 - 我认为您需要将同步块移到 while true 内。

或者,我会考虑使用 BlockingQueue,这样您就可以从您的代码中摆脱所有手动锁定。