Skip to content

Commit babb4ef

Browse files
author
arbhard2
committed
Embedded MultiThread Project
1 parent 404823e commit babb4ef

48 files changed

Lines changed: 2210 additions & 0 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

README.md

Whitespace-only changes.
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.ab.multithread.basics;
2+
3+
/**
4+
* @author Arpit Bhardwaj
5+
*
6+
* IllegalMonitorStateException which wait() and notify() methods throw when they get called from non-synchronized context
7+
* so obj.wait() and if this call throws an exception it means thread in Java is not holding the lock, otherwise thread holds the lock.
8+
*
9+
* thread static method called holdsLock(Object obj) which returns true or false based on
10+
* whether threads holds a lock on the object passed.
11+
*
12+
*/
13+
public class CheckHoldLock implements Runnable {
14+
public static void main(String[] args) {
15+
Thread t = new Thread(new CheckHoldLock());
16+
t.start();
17+
}
18+
19+
@Override
20+
public void run() {
21+
System.out.println("Holds Lock : " + Thread.holdsLock(this));
22+
synchronized (this){
23+
System.out.println("Holds Lock : " + Thread.holdsLock(this));
24+
}
25+
System.out.println("Holds Lock : " + Thread.holdsLock(this));
26+
}
27+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.ab.multithread.basics;
2+
3+
/**
4+
* @author Arpit Bhardwaj
5+
*/
6+
public class CurrentThreadStackTraceDemo {
7+
public static void main(String[] args) {
8+
first();
9+
}
10+
11+
private static void first() {
12+
second();
13+
}
14+
15+
private static void second() {
16+
third();
17+
}
18+
19+
private static void third() {
20+
21+
System.out.println("Stack trace of current thread using dumpStack() method");
22+
Thread.currentThread().dumpStack();
23+
24+
System.out.println("Printing stack trace using printStackTrace() method of Throwable ");
25+
new Throwable().printStackTrace();
26+
27+
//If you want stack trace as StackTraceElement in program itself than
28+
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
29+
for (StackTraceElement traceElement:
30+
stackTraceElements) {
31+
System.out.println(traceElement.getLineNumber() + " : " +traceElement.getMethodName());
32+
}
33+
}
34+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.ab.multithread.basics;
2+
3+
/**
4+
* @author Arpit Bhardwaj
5+
*
6+
* As soon as last nondaemon thread (user thread) finished JVM terminates no matter how many daemon thread exists or running inside JVM
7+
* It is an utmost low priority thread.
8+
*
9+
*/
10+
public class DaemonThread {
11+
public static void main(String[] args) throws InterruptedException {
12+
Thread t = new Thread(new Runnable() {
13+
@Override
14+
public void run() {
15+
String name = Thread.currentThread().getName();
16+
try {
17+
while (true){
18+
System.out.println("Running" + name);
19+
}
20+
}
21+
finally {
22+
System.out.println("Ending" + name);
23+
}
24+
25+
}
26+
});
27+
//throw IllegalThreadStateException if corresponding Thread is already started and running.
28+
29+
t.setName("Demon Thread 1");
30+
t.setDaemon(true);
31+
t.start();
32+
//t.join();//this will lead the main to wait for daemon to finish
33+
Thread.sleep(10);
34+
}
35+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.ab.multithread.basics;
2+
3+
/**
4+
* @author Arpit Bhardwaj
5+
* Exception occured in child thread does not end the parent Thread
6+
*
7+
* UncaughtExceptionHandler is a functional interface defined in Thread class can be used for making logging more robust only as well without restarting the thread
8+
* (1) t.setUncaughtExceptionHandler set the exception handler for the current thread
9+
* (2) Thread.setDefaultUncaughtExceptionHandler set the default exception handler for the entire
10+
*/
11+
public class ExceptionHandler {
12+
public static void main(String[] args) {
13+
Thread.UncaughtExceptionHandler exceptionHandler = new Thread.UncaughtExceptionHandler() {
14+
@Override
15+
public void uncaughtException(Thread t, Throwable e) {
16+
System.out.println(t.getName() + " Exception : " + e);
17+
}
18+
};
19+
20+
Thread t1 = new Thread(new Runnable() {
21+
@Override
22+
public void run() {
23+
System.out.println("Sleeping...");
24+
try {
25+
Thread.sleep(2000);
26+
} catch (InterruptedException e) {
27+
e.printStackTrace();
28+
}
29+
System.out.println("Throwing Exception...");
30+
throw new RuntimeException();
31+
}
32+
}, "Thread 1");
33+
34+
//set exception handler only for Thread 1
35+
//t1.setUncaughtExceptionHandler(exceptionHandler);
36+
//set the default exception handler for the entire
37+
Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);
38+
t1.start();
39+
try {
40+
Thread.sleep(4000);
41+
} catch (InterruptedException e) {
42+
e.printStackTrace();
43+
}
44+
throw new RuntimeException();
45+
}
46+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.ab.multithread.basics;
2+
3+
/**
4+
* @author Arpit Bhardwaj
5+
*
6+
* Thread in Java will stop once run() method finished
7+
* you can not restart a Thread which run() method has finished already , you will get an IllegalStateExceptio
8+
*
9+
* Manual Stop Mechanism shown below
10+
*/
11+
public class FlagStop {
12+
static class StopEnabledTask extends Thread {
13+
boolean exit = false;
14+
15+
public void setExit(boolean exit) {
16+
this.exit = exit;
17+
}
18+
19+
@Override
20+
public void run() {
21+
while (!exit){
22+
System.out.println("Running Thread...");
23+
try {
24+
Thread.sleep(500);
25+
} catch (InterruptedException e) {
26+
e.printStackTrace();
27+
}
28+
}
29+
System.out.println("Stopping Thread...");
30+
}
31+
}
32+
public static void main(String[] args) throws InterruptedException {
33+
StopEnabledTask t = new StopEnabledTask();
34+
t.setName("Thread 1");
35+
t.start();
36+
Thread.sleep(1000);
37+
t.setExit(true);
38+
}
39+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.ab.multithread.basics;
2+
3+
/**
4+
* @author Arpit Bhardwaj
5+
* The instance interrupt() method sets the interrupted flag
6+
* The instance isInterrupted() method returns the interrupted flag either true or false.
7+
* The static interrupted() method returns the interrupted flag afterthat it sets the flag to false if it is true.
8+
*
9+
* When thread is in running state, the interrupt signal has no effect untill its coded to check isInterrupted
10+
* When the thread is in waiting and timed waiting state, the interrupt signal produce InterruptedException else not
11+
*/
12+
public class InterruptStop {
13+
public static void main(String[] args) throws InterruptedException {
14+
Thread t = new Thread(new Runnable() {
15+
@Override
16+
public void run() {
17+
//while (!t.isInterrupted()){
18+
while (!Thread.interrupted()){
19+
System.out.println("Running Thread...");
20+
}
21+
22+
System.out.println("Stopping Thread...");
23+
}
24+
});
25+
26+
t.start();
27+
Thread.sleep(1);
28+
t.interrupt();
29+
Thread.sleep(1);
30+
System.out.println(t.isInterrupted());
31+
}
32+
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package com.ab.multithread.basics;
2+
3+
//import com.sun.org.apache.xpath.internal.operations.Mult;
4+
5+
/**
6+
* @author Arpit Bhardwaj
7+
*
8+
* Threads can be created by using two mechanisms :
9+
* Extending the Thread class
10+
* Implementing the Runnable Interface (Recommended)
11+
*
12+
* If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance
13+
* Using runnable will give you an object that can be shared amongst multiple threads.
14+
*
15+
* Thread Lifecycle
16+
* NEW : Thread has not yet started
17+
* RUNNABLE : Thread is executing
18+
* BLOCKED : Thread is blocked, waiting for monitor lock to be released
19+
* WAITING : Thread is waiting as long as it takes for another thread's signal
20+
* TIMED_WAITING : Thread is waiting for a specified period of time
21+
* TERMINATED : Thread is exited
22+
*/
23+
public class MultiThreadDemo {
24+
public static void main(String[] args) throws InterruptedException {
25+
System.out.println(Thread.currentThread().getName() + " is running");
26+
27+
Runnable runnable1 = ()-> {System.out.println("I am running in " + Thread.currentThread().getName());};
28+
Thread t1 = new Thread(runnable1);
29+
t1.setName("Thread t1");
30+
//The purpose of start() is to create a separate call stack for the thread.
31+
// A separate call stack is created by it, and then run() is called by JVM.
32+
t1.start();
33+
//t1.run(); //not run as a separate thread instead as part of main thread
34+
35+
MultiThread1 t2 = new MultiThread1();
36+
t2.setName("Thread t2");
37+
t2.start();
38+
//It will put the current thread on wait until the thread on which it is called is dead.
39+
t2.join();
40+
41+
Runnable runnable2 = new MultiThread2();
42+
Thread t3 = new Thread(runnable2);
43+
t3.setName("Thread t3");
44+
t3.start();
45+
//It will put the current thread on wait until the thread on which it is called is dead or wait for specified time
46+
t3.join(10);
47+
48+
System.out.println(Thread.currentThread().getName() + " is finished");
49+
}
50+
51+
static class MultiThread1 extends Thread{
52+
@Override
53+
public void run() {
54+
System.out.println(Thread.currentThread().getName() + " is running");
55+
try {
56+
Thread.sleep(100);
57+
} catch (InterruptedException e) {
58+
e.printStackTrace();
59+
}
60+
61+
System.out.println(Thread.currentThread().getName() + " is finished");
62+
}
63+
}
64+
65+
static class MultiThread2 implements Runnable{
66+
@Override
67+
public void run() {
68+
System.out.println(Thread.currentThread().getName() + " is running");
69+
try {
70+
Thread.sleep(1000);
71+
} catch (InterruptedException e) {
72+
e.printStackTrace();
73+
}
74+
75+
System.out.println(Thread.currentThread().getName() + " is finished");
76+
}
77+
}
78+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package com.ab.multithread.basics;
2+
3+
/**
4+
* @author Arpit Bhardwaj
5+
*
6+
* Race condition
7+
* is a type of concurrency bug or issue which is introduced in your program because of parallel execution.
8+
* example is incrementing a counter which is not an atomic operation and can be further divided into three steps like read, update and write.
9+
*
10+
*/
11+
12+
public class RaceCondition {
13+
14+
private static class LongWrapper {
15+
private long l;
16+
private Object key = new Object();
17+
public LongWrapper(long l) {
18+
this.l = l;
19+
}
20+
21+
public long getL() {
22+
return l;
23+
}
24+
25+
public void incrementL() {
26+
synchronized (key){
27+
l = l + 1 ;
28+
}
29+
}
30+
}
31+
32+
public static void main(String[] args) throws InterruptedException {
33+
LongWrapper longWrapper = new LongWrapper(0L);
34+
35+
Runnable task = () -> {
36+
for (int i = 0; i < 1000; i++) {
37+
longWrapper.incrementL();
38+
}
39+
};
40+
41+
/*Thread t = new Thread(task);
42+
t.start();
43+
t.join();*/
44+
45+
Thread[] threads = new Thread[1000];
46+
for (int i = 0; i < threads.length; i++) {
47+
threads[i] = new Thread(task);
48+
threads[i].start();
49+
}
50+
for (int i = 0; i < threads.length; i++) {
51+
threads[i].join();
52+
}
53+
System.out.println("Value = " + longWrapper.getL());
54+
}
55+
}

0 commit comments

Comments
 (0)