0

here is my thread code

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

here is my member field

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

and here is my method

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

the prioritqueue is using by another thread but i made it synchronized by using a queueLock object. the method decoding is not working in docode thread!!!

mjdcsy
  • 17
  • 6

1 Answers1

0

I think you can drop the queueLock object and lock on the queue itself.

The way you currently have your code structured the monitor will never be released - I think you need to move the synchronization block inside the while true.

Alternatively I would look at using a BlockingQueue so you can get ride of all the manual locking from your code.

Lee
  • 738
  • 3
  • 13
  • the program sharing the queue with another thread. i put the synchronized block in while loop and i think it works! – mjdcsy May 05 '16 at 07:54
  • You are using very old Java axioms for this - this would be an excellent fit for a ThreadPool and an ExecutorCompletionService – Lee May 05 '16 at 07:58