Close

Java - java.lang.Thread Examples

Java 

public class ThreadExample {
public static void main (String[] args) {
MyThread thread = new MyThread();
thread.start();

Thread thread2 = new MyThread();
thread2.start();

System.out.println(Thread.currentThread()
.getName());
}

private static class MyThread extends Thread {
@Override
public void run () {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread()
.getName() + ": " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Original Post




public class ThreadRunnableExample {

public static void main (String[] args) {
MyThreadRunner threadRunnable = new MyThreadRunner();
Thread thread = new Thread(threadRunnable);
thread.start();

MyThreadRunner threadRunnable2 = new MyThreadRunner();
Thread thread2 = new Thread(threadRunnable2);

thread2.start();

System.out.println(Thread.currentThread()
.getName());
}

private static class MyThreadRunner implements Runnable {
@Override
public void run () {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread()
.getName() + ": " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Original Post




public class MemoryWatcherThread implements Runnable {
public static void start () {
Thread thread = new Thread(new MemoryWatcherThread());
thread.setPriority(Thread.MAX_PRIORITY);
thread.setDaemon(true);
thread.start();
}

@Override
public void run () {

long memoryUsed = getMemoryUsed();
System.out.println("Memory used :" + memoryUsed + " MB");

while (true) {
long memoryUsed1 = getMemoryUsed();
if (memoryUsed != memoryUsed1) {
memoryUsed = memoryUsed1;
System.out.println("Memory used :" + memoryUsed + " MB");
}
}
}

private long getMemoryUsed () {
return (Runtime.getRuntime()
.totalMemory() - Runtime.getRuntime()
.freeMemory()) / 1024 / 1024;
}

}
Original Post




Thread priority example.

public class ThreadPriorityExample {
public static void main (String[] args) {
MyThread thread = new MyThread();
thread.setName("thread 1");
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();

Thread thread2 = new MyThread();
thread2.setName("thread 2");
thread2.setPriority(Thread.MAX_PRIORITY);
thread2.start();
}

private static class MyThread extends Thread {
private int c;

@Override
public void run () {
String threadName = Thread.currentThread()
.getName();

System.out.println(threadName + " started.");
for (int i = 0; i < 1000; i++) {
c++;
try {
TimeUnit.MICROSECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(threadName + " ended.");
}
}
}
Original Post

Thread#yield() example.

public class ThreadYieldExample {
public static void main (String[] args) {
Task task1 = new Task(true);
new Thread(task1).start();

Task task2 = new Task(false);
new Thread(task2).start();

}

private static class Task implements Runnable {
private final boolean shouldYield;
private int c;

public Task(boolean shouldYield){
this.shouldYield = shouldYield;
}
@Override
public void run () {
String threadName = Thread.currentThread()
.getName();

System.out.println(threadName + " started.");
for (int i = 0; i < 1000; i++) {
c++;
if(shouldYield){
Thread.yield();
}
}

System.out.println(threadName + " ended.");
}
}
}
Original Post




Thread#join() example.

public class ThreadJoinExample {
public static void main (String[] args) throws InterruptedException {
Task task1 = new Task();
Thread thread1 = new Thread(task1);
thread1.start();
thread1.join();//here the main thread will wait until thread1 fishes.
System.out.println("after join");

Task task2 = new Task();
new Thread(task2).start();
}

private static class Task implements Runnable {

@Override
public void run () {
int c = 0;
String threadName = Thread.currentThread()
.getName();

System.out.println(threadName + " started.");
for (int i = 0; i < 1000; i++) {
c+=i;
}

System.out.println(threadName + " ended.");
}
}
}
Original Post




Thread#join() example

public class ThreadJoinExample2 {
public static void main (String[] args) {
final List<Integer> integers = Arrays.asList(10, 12, 13, 14, 15, 20);

new Thread(new Runnable() {
@Override
public void run () {
List<FactorialCalculator> threads = new ArrayList<>();
for (Integer integer : integers) {
FactorialCalculator calc = new FactorialCalculator(integer);
threads.add(calc);
calc.start();
}
for (FactorialCalculator calc : threads) {
try {
calc.join();
System.out.println(calc.getNumber() + "! = " + calc.getFactorial());

} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}

private static class FactorialCalculator extends Thread {

private final int number;
private BigDecimal factorial;

FactorialCalculator (int number) {
this.number = number;
}

@Override
public void run () {
factorial = calculateFactorial(number);
}

private static BigDecimal calculateFactorial (int number) {
BigDecimal factorial = BigDecimal.ONE;
for (int i = 1; i <= number; i++) {
factorial = factorial.multiply(new BigDecimal(i));
}
return factorial;
}


public BigDecimal getFactorial () {
return factorial;
}

public int getNumber () {
return number;
}
}
}
Original Post

Thread#interrup() example.

public class ThreadInterruptExample {
public static void main (String[] args) throws InterruptedException {
Task task1 = new Task();
Thread thread1 = new Thread(task1);
thread1.start();
while (true){
if(Math.random()>0.5){
thread1.interrupt();
break;
}
TimeUnit.MILLISECONDS.sleep(1);
}
}

private static class Task implements Runnable {

@Override
public void run () {
int c = 0;

while (true) {

System.out.println("task running .. " + ++c);
if (Thread.currentThread()
.isInterrupted()) {
System.out.println("interrupted flag=true");
terminate();
return;
}
try {
TimeUnit.MICROSECONDS.sleep(1);
} catch (InterruptedException e) {
System.out.println("interrupted exception ");
terminate();
return;
}
}

}

private void terminate () {
System.out.println("Terminating task");
}
}
}
Original Post




Thread#interrupt example

public class ThreadInterruptSwingDemo {
public static void main (String[] args) {
JFrame frame = new JFrame("Interrupt Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(500, 500));
frame.add(createAnimationContainer());
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

private static Component createAnimationContainer () {
JPanel panel = new JPanel(new BorderLayout());
AnimatedPanel animatedPanel = new AnimatedPanel();
panel.add(animatedPanel);
JButton button = new JButton("Reverse");
panel.add(button, BorderLayout.SOUTH);
button.addActionListener(e -> {
animatedPanel.getThread().interrupt();

});
return panel;
}

private static class AnimatedPanel extends JComponent {
private int angle = 0;
boolean clockwise = true;
private Thread thread;

AnimatedPanel () {
startAnimation();
}

private void startAnimation () {
thread = new Thread(() -> {
while (true) {
angle++;
if (angle >= 360) {
angle = 0;
}
if(thread.isInterrupted()){
clockwise = !clockwise;
}
//no need to create EDT
repaint();
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
clockwise = !clockwise;

}
}
});
thread.start();

}

@Override
public void paint (Graphics g) {
g.setColor(Color.MAGENTA);
g.fillArc(10, 10, 400, 400, clockwise? -angle: angle, 30 );
}

public Thread getThread () {
return thread;
}
}
}
Original Post




Thread synchronized method example

public class ThreadSynchronizedDemo {
private Integer counter = 0;

public static void main (String[] args) throws InterruptedException {
ThreadSynchronizedDemo demo = new ThreadSynchronizedDemo();
Task task1 = demo.new Task();
Thread thread1 = new Thread(task1);

Task task2 = demo.new Task();
Thread thread2 = new Thread(task2);

thread1.start();
thread2.start();
}

private synchronized void performTask () {
int temp = counter;
counter++;
System.out.println(Thread.currentThread()
.getName() + " - before: "+temp+" after:" + counter);
}

private class Task implements Runnable {

@Override
public void run () {
for (int i = 0; i < 5; i++) {
performTask();
}
}
}
}

Thread synchronized static method example.

public class ThreadSynchronizedStaticDemo {
private static Integer counter = 0;

public static void main (String[] args) throws InterruptedException {
Task task1 = new Task();
Thread thread1 = new Thread(task1);

Task task2 = new Task();
Thread thread2 = new Thread(task2);

thread1.start();
thread2.start();
}

private static void performTask () {
int temp = counter;
counter++;
System.out.println(Thread.currentThread()
.getName() + " - before: "+temp+" after:" + counter);
}

private static class Task implements Runnable {

@Override
public void run () {
for (int i = 0; i < 5; i++) {
performTask();
}
}
}
}




Thread interference example

public class ThreadInterferenceDemo {
private Integer counter = 0;

public static void main (String[] args) throws InterruptedException {
ThreadInterferenceDemo demo = new ThreadInterferenceDemo();
Task task1 = demo.new Task();
Thread thread1 = new Thread(task1);

Task task2 = demo.new Task();
Thread thread2 = new Thread(task2);

thread1.start();
thread2.start();
}

private void performTask () {
int temp = counter;
counter++;
System.out.println(Thread.currentThread()
.getName() + " - before: " + temp + " after:" + counter);
}

private class Task implements Runnable {

@Override
public void run () {
for (int i = 0; i < 5; i++) {
performTask();
}
}
}
}
Original Post




Thread synchronized method example

public class ThreadSynchronizedDemo {
private Integer counter = 0;

public static void main (String[] args) throws InterruptedException {
ThreadSynchronizedDemo demo = new ThreadSynchronizedDemo();
Task task1 = demo.new Task();
Thread thread1 = new Thread(task1);

Task task2 = demo.new Task();
Thread thread2 = new Thread(task2);

thread1.start();
thread2.start();
}

private synchronized void performTask () {
int temp = counter;
counter++;
System.out.println(Thread.currentThread()
.getName() + " - before: "+temp+" after:" + counter);
}

private class Task implements Runnable {

@Override
public void run () {
for (int i = 0; i < 5; i++) {
performTask();
}
}
}
}
Original Post
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

public class MultipleSyncMethodsDemo {

public static void main (String[] args) throws InterruptedException {
MultipleSyncMethodsDemo demo = new MultipleSyncMethodsDemo();
Thread thread1 = new Thread(() -> {
System.out.println("thread1 before call " + LocalDateTime.now());
demo.syncMethod1("from thread1");
System.out.println("thread1 after call " + LocalDateTime.now());
});
Thread thread2 = new Thread(() -> {
System.out.println("thread2 before call " + LocalDateTime.now());
demo.syncMethod2("from thread2");
System.out.println("thread2 after call " + LocalDateTime.now());
});

thread1.start();
thread2.start();
}

private synchronized void syncMethod1 (String msg) {
System.out.println("in the syncMethod1 " + msg + " " + LocalDateTime.now());
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

private synchronized void syncMethod2 (String msg) {
System.out.println("in the syncMethod2 " + msg + " " + LocalDateTime.now());
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Original Post




import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

public class ThreadLockDemo {

public static void main (String[] args) throws InterruptedException {
ThreadLockDemo demo = new ThreadLockDemo();
Thread thread1 = new Thread(() -> {
System.out.println("thread1 before call "+ LocalDateTime.now());
demo.syncMethod("from thread1");
System.out.println("thread1 after call "+LocalDateTime.now());
});
Thread thread2 = new Thread(() -> {
System.out.println("thread2 before call "+LocalDateTime.now());
demo.syncMethod("from thread2");
System.out.println("thread2 after call "+LocalDateTime.now());
});

thread1.start();
thread2.start();
}

private synchronized void syncMethod (String msg) {
System.out.println("in the sync method "+msg+" "+LocalDateTime.now());
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Original Post




import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

public class ThreadStaticSyncDemo {

public static void main (String[] args) throws InterruptedException {

Thread thread1 = new Thread(() -> {
System.out.println("thread1 before call "+ LocalDateTime.now());
syncMethod("from thread1");
System.out.println("thread1 after call "+LocalDateTime.now());
});
Thread thread2 = new Thread(() -> {
System.out.println("thread2 before call "+LocalDateTime.now());
syncMethod("from thread2");
System.out.println("thread2 after call "+LocalDateTime.now());
});

thread1.start();
thread2.start();
}

private static synchronized void syncMethod (String msg) {
System.out.println("in the sync method "+msg+" "+LocalDateTime.now());
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Original Post




import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

public class ReentrantDemo {

public static void main (String[] args) throws InterruptedException {
ReentrantDemo demo = new ReentrantDemo();
Thread thread1 = new Thread(() -> {
System.out.println("thread1 before call " + LocalDateTime.now());
demo.syncMethod1("from thread1");
System.out.println("thread1 after call " + LocalDateTime.now());
});
Thread thread2 = new Thread(() -> {
System.out.println("thread2 before call " + LocalDateTime.now());
demo.syncMethod2("from thread2");
System.out.println("thread2 after call " + LocalDateTime.now());
});

thread1.start();
thread2.start();
}

private synchronized void syncMethod1 (String msg) {
System.out.println("in the syncMethod1 " + msg + " " + LocalDateTime.now());
syncMethod2("from method syncMethod1, reentered call");
}

private synchronized void syncMethod2 (String msg) {
System.out.println("in the syncMethod2 " + msg + " " + LocalDateTime.now());
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Original Post




Synchronized block Example

import java.util.ArrayList;
import java.util.List;

public class LazyInitBlockDemo {
private volatile List<String> list;

public static void main (String[] args) throws InterruptedException {
LazyInitBlockDemo obj = new LazyInitBlockDemo();

Thread thread1 = new Thread(() -> {
System.out.println("thread1 : " + System.identityHashCode(obj.getList()));
});
Thread thread2 = new Thread(() -> {
System.out.println("thread2 : " + System.identityHashCode(obj.getList()));
});

thread1.start();
thread2.start();
}

private List<String> getList () {
if (list == null) {
synchronized (this) {
if(list == null) {
list = new ArrayList<>();
}
}
}
return list;
}
}
Original Post




Synchronized block Example

import java.util.ArrayList;
import java.util.List;

public class MultipleLocksDemo {
private volatile List<String> list1;
private volatile List<String> list2;
private final Object lock1 = new Object();
private final Object lock2 = new Object();

public static void main (String[] args) throws InterruptedException {
MultipleLocksDemo obj = new MultipleLocksDemo();

Thread thread1 = new Thread(() -> {
System.out.println("thread1 list1 : " + System.identityHashCode(obj.getList1()));
System.out.println("thread1 list2 : " + System.identityHashCode(obj.getList2()));
});
Thread thread2 = new Thread(() -> {
System.out.println("thread2 list1 : " + System.identityHashCode(obj.getList1()));
System.out.println("thread2 list2 : " + System.identityHashCode(obj.getList2()));
});

thread1.start();
thread2.start();
}

private List<String> getList1 () {
if (list1 == null) {
synchronized (lock1) {
if (list1 == null) {
list1 = new ArrayList<>();
}
}
}
return list1;
}

private List<String> getList2 () {
if (list2 == null) {
synchronized (lock2) {
if (list2 == null) {
list2 = new ArrayList<>();
}
}
}
return list2;
}
}
Original Post




Synchronized block Example

import java.util.ArrayList;
import java.util.List;

public class MultipleLocksDemo2 {
private List<String> list1 = new ArrayList<>();
private List<String> list2 = new ArrayList<>();

public static void main (String[] args) {
MultipleLocksDemo2 obj = new MultipleLocksDemo2();

Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
obj.addToList1("thread1 list1 element=" + i);
obj.addToList2("thread1 list2 element=" + i);
obj.printLists();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
obj.addToList1("thread2 list1 element=" + i);
obj.addToList2("thread2 list2 element 2" + i);
obj.printLists();
}
});

thread1.start();
thread2.start();

}

public void addToList1 (String s) {
synchronized (list1) {
list1.add(s);
}
}

public void addToList2 (String s) {
synchronized (list2) {
list2.add(s);
}
}

public void printLists () {
String name = Thread.currentThread()
.getName();

synchronized (list1) {
list1.stream()
.forEach(l -> System.out.println(name + " : " + l));
}
synchronized (list2) {
list2.stream()
.forEach(l -> System.out.println(name + " : " + l));
}
}
}
Original Post




Synchronized block Example

public class SyncBlockStringLock {
private Map<String, Object> locks = new HashMap<>();

private static final File rootFolder = new File("d:\\test");

static {
if (!rootFolder.exists()) {
rootFolder.mkdir();
}
}

public static void main (String[] args) {
SyncBlockStringLock obj = new SyncBlockStringLock();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
String path = rootFolder.getAbsolutePath() + File.separatorChar + i;
obj.writeData(path, " thread1 data " + i);
obj.readData(path);
}
});

Thread thread2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
String path = rootFolder.getAbsolutePath() + File.separatorChar + i;
obj.writeData(path, " thread2 data " + i);
obj.readData(path);
}
});

thread1.start();
thread2.start();
}

private void writeData (String path, String data) {
synchronized (getLock(path)) {
try {
Files.write(Paths.get(path), data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}

private void readData (String path) {
synchronized (getLock(path)) {
String s = null;
try {
s = new String(Files.readAllBytes(Paths.get(path)));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(s);
}
}

private Object getLock (String path) {
if (!locks.containsKey(path)) {
locks.put(path, new Object());
}

return locks.get(path);
}
}
Original Post




DeadLock Example

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class DeadLockDemo {

public static void main (String[] args) throws InterruptedException {
List<Integer> list1 = new ArrayList<>(Arrays.asList(2, 4, 6, 8, 10));
List<Integer> list2 = new ArrayList<>(Arrays.asList(1, 3, 7, 9, 11));

Thread thread1 = new Thread(() -> {
moveListItem(list1, list2, 2);
});
Thread thread2 = new Thread(() -> {
moveListItem(list2, list1, 9);
});

thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(list1);
System.out.println(list2);
}

private static void moveListItem (List<Integer> from, List<Integer> to, Integer item) {
log("attempting lock for list", from);
synchronized (from) {
log("lock acquired for list", from);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
log("attempting lock for list ", to);
synchronized (to) {
log("lock acquired for list", to);
if(from.remove(item)) {
to.add(item);
}
log("moved item to list ", to);
}
}
}

private static void log (String msg, Object target) {
System.out.println(Thread.currentThread().getName() +
": " + msg + " " +
System.identityHashCode(target));
}
}
Original Post




DeadLock Fix Example

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class DeadLockFixDemo {

public static void main (String[] args) throws InterruptedException {
List<Integer> list1 = new ArrayList<>(Arrays.asList(2, 4, 6, 8, 10));
List<Integer> list2 = new ArrayList<>(Arrays.asList(1, 3, 7, 9, 11));

Thread thread1 = new Thread(() -> {
moveListItem(list1, list2, 2);
});
Thread thread2 = new Thread(() -> {
moveListItem(list2, list1, 9);
});

thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(list1);
System.out.println(list2);
}

private static void moveListItem (List<Integer> from, List<Integer> to, Integer item) {
log("attempting lock for list", from);
boolean removedSuccessful = false;

synchronized (from) {
log("lock acquired for list", from);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
removedSuccessful = from.remove(item);
}
if (removedSuccessful) {
log("attempting lock for list ", to);
synchronized (to) {
log("lock acquired for list", to);

to.add(item);
log("moved item to list ", to);
}
}
}

private static void log (String msg, Object target) {
System.out.println(Thread.currentThread()
.getName() +
": " + msg + " " +
System.identityHashCode(target));
}
}
Original Post




wait and notify example

public class SimpleWaitNotifyDemo {
private static String message;

public static void main (String[] args) {
Object lock = new Object();

Thread thread1 = new Thread(() -> {
synchronized (lock) {
while (message == null) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

System.out.println(message);
});

Thread thread2 = new Thread(() -> {
synchronized (lock) {
message = "A message from thread1";
lock.notify();
}
});

thread1.start();
thread2.start();
}
}
Original Post




wait and notify example

public class WaitNotifyDemo {

public static void main (String[] args) {
SharedObject obj = new SharedObject();

Thread thread1 = new Thread(() -> {
obj.printMessage();
});

Thread thread2 = new Thread(() -> {
obj.setMessage("A message from thread1");
});

thread1.start();
thread2.start();
}

private static class SharedObject {
private String message;

public synchronized void setMessage (String message) {
this.message = message;
notify();
}

public synchronized void printMessage () {
while (message == null) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(message);

}
}
}
Original Post




See Also