From the course: Advanced Java Programming

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Avoiding thread deadlock

Avoiding thread deadlock - Java Tutorial

From the course: Advanced Java Programming

Start my 1-month free trial

Avoiding thread deadlock

- [Narrator] A deadlock can occur when two or more threats get blocked forever. For example, this can happen when two threats are both waiting for resources held by each other. In this example, I am simulating a situation with two cooks in a kitchen. Imagine if both cooks wanted to mix some ingredients, so they both need a spoon and a bowl. However, there is only one spoon and one bowl. The first cook picks up the spoon and at the same time, the second cook picks up the bowl. Now both cooks are waiting for the other one to put down their object so they can pick it up. This is a deadlock. To simulate this, I have a class called kitchen with two objects called spoon and bowl. Then in the main method, I have two threads which represent the two cooks. So I have called them cook one and cook two. Inside the first thread is a synchronized block. A synchronized block or synchronized statement is a section of codes that only one thread can enter at a time. This means that you can have…

Contents