Skip to content

Instantly share code, notes, and snippets.

@panwarab
Last active May 27, 2019 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panwarab/6d18c7b8a87abb752fccb55512d5a3c7 to your computer and use it in GitHub Desktop.
Save panwarab/6d18c7b8a87abb752fccb55512d5a3c7 to your computer and use it in GitHub Desktop.
package core.src.thread;
import java.util.Arrays;
public class Thread {
public static void main(String[] args) {
A a=new A();
new java.lang.Thread(new RunA(a)).start();
new java.lang.Thread(new RunB(a)).start();
}
}
class RunA implements Runnable{
private final A a;
RunA(A a){
this.a=a;
}
@Override
public void run() {
while(true) {
a.print(java.lang.Thread.currentThread().getName());
Arrays.stream(java.lang.Thread.currentThread().getStackTrace()).forEach(System.out::println);
try {
java.lang.Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class RunB implements Runnable{
private final A a;
RunB(A a){
this.a=a;
}
@Override
public void run() {
while (true) {
a.print(java.lang.Thread.currentThread().getName());
Arrays.stream(java.lang.Thread.currentThread().getStackTrace()).forEach(System.out::println);
try {
java.lang.Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class A{
void print(String a){
// Will this object get overridden by another Thread B, if A leaves control in the middle?
Object a=new Object();
// add another ten lines of code where it is possible that thread A might give up control
// .... Current Thread leaves control ....
System.out.println("Hello from "+a);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment