【问题标题】:method and lock issue in thread线程中的方法和锁定问题
【发布时间】:2016-08-30 22:01:29
【问题描述】:

这是我的线程代码

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 中不起作用!!!

【问题讨论】:

  • 你排的怎么样?
  • 为什么同步块中有无限循环?你希望那把锁永远解锁吗?
  • @Lee 我正在用另一个线程填充它
  • @JonnyHenly 我应该使用 notify() 来解锁吗?

标签: java multithreading methods locking synchronized


【解决方案1】:

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

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

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

【讨论】:

  • 程序与另一个线程共享队列。我将同步块放在while循环中,我认为它有效!
  • 您为此使用了非常古老的 Java 公理 - 这非常适合 ThreadPool 和 ExecutorCompletionService
猜你喜欢
  • 2020-08-28
  • 1970-01-01
  • 2018-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多