Summary - Multithreading
- Java course
- Advanced
- Lesson 60/82
- 5 min
Combine Thread, Runnable and synchronized to write a counter.
Summary - Multithreading
In this group you saw Java's core thread tools: the Thread class, the Runnable interface, start and join, mutual exclusion with synchronized, and thread communication with wait/notify.
Now you will combine these into a mini task: building a TaskQueue structure. This summary shows how a concurrent data structure is written.
Practice Apply synchronized with a TaskQueue
Define a TaskQueue class with a private int size = 0 field. A public synchronized void add() method does size++. A public synchronized int size() method returns size. In a QueueDemo class write main; create a TaskQueue instance, call add() three times and print size().
Starter code
// Define the TaskQueue class (size field, synchronized add and size)
// Write main in QueueDemo; call add three times and print size's resultSample solution
class TaskQueue {
private int size = 0;
public synchronized void add() {
size++;
}
public synchronized int size() {
return size;
}
}
class QueueDemo {
public static void main(String[] args) {
TaskQueue q = new TaskQueue();
q.add();
q.add();
q.add();
System.out.println(q.size());
}
}Expected output
3
Practice Apply Thread inheritance with WorkerThread
Define a WorkerThread class that extends Thread; in @Override public void run() call System.out.println("Worker ready"). In a WorkerDemo class write main; create a WorkerThread instance and call run() directly.
Starter code
// Define WorkerThread extending Thread
// Call println in run()
// Write main in WorkerDemo and call run()Sample solution
class WorkerThread extends Thread {
@Override
public void run() {
System.out.println("Worker ready");
}
}
class WorkerDemo {
public static void main(String[] args) {
new WorkerThread().run();
}
}Expected output
Worker ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is used to wait for a thread to finish?
- start()
- run()
- yield()
- join() Correct answer
Explanation: join() waits for the thread to finish.
2 Match the Multithreading summary
| Term | Meaning |
|---|---|
Thread |
Thread class |
Runnable |
Task interface |
synchronized |
Mutual exclusion |
wait/notify |
Communication |