title: How to guarantee two statements will execute sequentially without being interrupted by another thread
body: <p>In a simple Java program, I have two Threads running, <code>addSome</code> and <code>subtractSome</code>.</p>
  
  <p>These two Threads are both working on the same <code>box</code> object. So essentially, they are both adding and subtracting items from this box, concurrently. </p>
  
  <p>For the purpose of understanding threads and such, I am trying to output the content of the boxes and the Thread that is currently working.</p>
  
  <pre><code>System.out.println(Thread.currentThread().getName());
  System.out.println("Items: " + contents);
  </code></pre>
  
  <p>The problem is, I realized, because of the structure of the <code>if</code> statements in the <code>Box</code> class (you can only take items when there are items in the box etc) that the first output statement is printing <strong>and then</strong> switching to the other Thread where new contents are being added and then coming back to the first Thread where the old contents are being printed out. </p>
  
  <p>Basically, I want to make sure that both those statements are executed at the same time by the same thread and nothing should happen in between.</p>