Understanding Java Threads and Concurrency
Textual Information
In Java, a thread represents a single flow of execution within a program. Think of it as a factory with each worker(Thread) working independently on their task and concurrently alongside the other factory workers(Threads).
Video Information
Code Snippets
//Threads when Implementing Runnable
public class MyThread implements Runnable {
public void run() {
System.out.println("Running!");
}
public static void main(String[] args) {
MyThread t = new MyThread();
Thread toRun = new Thread(t);
toRun.start();
}
}
//Threads when Extending Thread
public class MyThreadTwo extends Thread {
public void run() {
System.out.println("Running!");
}
public static void main(String[] args) {
MyThreadTwo toRun = new MyThreadTwo();
toRun.start();
}
}
//Using Synchronized Block to Avoid Race Conditions
public class MyThread implements Runnable {
private static ArrayList nums;
public static final Object key = new Object();
public MyThread() {
if(nums == null) {
synchronized(key) {
if(nums == null) {
nums = new ArrayList();
}
}
}
}
public void run() {
for(int i = 0; i < 100; i++) {
synchronized(key) {
nums.add(i);
}
}
}
public static void main(String[] args) {
MyThread t = new MyThread();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
t1.start();
t2.start();
t3.start();
try {
t1.join();
t2.join();
t3.join();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
Quiz
Test your knowledge on Java Threads and Concurrency: