CodyBugstein
CodyBugstein

Reputation: 23342

How to guarantee two statements will execute sequentially without being interrupted by another thread

In a simple Java program, I have two Threads running, addSome and subtractSome.

These two Threads are both working on the same box object. So essentially, they are both adding and subtracting items from this box, concurrently.

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.

System.out.println(Thread.currentThread().getName());
System.out.println("Items: " + contents);

The problem is, I realized, because of the structure of the if statements in the Box class (you can only take items when there are items in the box etc) that the first output statement is printing and then 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.

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.

Upvotes: 0

Views: 178

Answers (2)

Java Enthusiast
Java Enthusiast

Reputation: 664

Use the concept of Thread Synchronization

It uses of concept of acquiring locks which will allow you to achieve your objective

Upvotes: 1

Sanojit
Sanojit

Reputation: 57

use synchronized concepts either synchronized method or synchronized block.

Upvotes: 3

Related Questions