title: Java lock and unlock on different thread
body: <p>I have a main thread and a worker thread. The main thread adds tasks into a queue and the worker thread takes them to compute data. Before I put the objects into the queue I call lock on a ReentrantLock object (<strong>on the main thread</strong>) inside the task objects. When the worker thread is finished with working on a task from the queue I call unlock (<strong>on the worker thread</strong>). The problem is that I get an IllegalMonitorStateException because I call lock and unlock on different threads.</p>
  
  <p>I am looking for an alternative lock system where I can do this on different threads.</p>
  
  <p>Example:</p>
  
  <pre><code>public class Worker extends Thread {
      public static Queue&lt;Task&gt; tasks = new ConcurrentLinkedQueue&lt;Task&gt;();
  
      @Override
      public void run() {
          while (true) {
              Task task = tasks.poll();
  
              if (task != null) {
                  task.work();
                  task.lock.unlock(); // Here is the unlock, Task#i should not change up to now
              }
          }
      }
  }
  
  
  public class Task {
      private int i = 0;
      public Lock lock;
  
      public void setI(int i) {
          lock.lock();
          this.i = i;
          lock.unlock();
      }
  
      public void work() {
          System.out.println(i);
      }
  }
  
  
  public class Test {
      Task task = new Task();
  
      public void addTask() {
          task.lock.lock(); // Here is the lock, Task#i should not change
          Worker.tasks.add(task);
      }
  }
  </code></pre>