Java Multithreaded Programming - Chit Sheet
Java Thread Model
- Thread: A lightweight sub-process; smallest unit of processing.
- Creating Threads:
* Extend Thread class:
class MyThread extends Thread {
public void run() {
[Link]("Thread running...");
new MyThread().start();
* Implement Runnable interface:
class MyRunnable implements Runnable {
public void run() {
[Link]("Runnable thread running...");
new Thread(new MyRunnable()).start();
Synchronization
- Race Condition: Multiple threads access and modify shared data.
- Use synchronized keyword:
synchronized void method() {
// thread-safe code
- Synchronized block:
synchronized(obj) {
// critical section
Runnable Interface
Java Multithreaded Programming - Chit Sheet
- Used to create threads without extending Thread class.
- Method: public void run()
- Example with lambda:
Runnable r = () -> [Link]("Using Lambda!");
new Thread(r).start();
Collections Overview
- List (ordered, allows duplicates):
* ArrayList, LinkedList
* Methods: add(), get(), remove()
- Set (unordered, no duplicates):
* HashSet, LinkedHashSet, TreeSet
* Methods: add(), contains(), remove()
- Map (key-value pairs):
* HashMap, TreeMap, LinkedHashMap
* Methods: put(), get(), remove()