What's the difference in flow creation using Thread and Runnable?
-
And if you're more specific, that's what. Let's say we have a code, like,
public class Main{ public static void main(String[] args) { MyThread myThread = new MyThread(); Thread t1 = new Thread(myThread); t1.start(); myThread.sysOut(); } }
public class MyThread implements Runnable {
public void run(){
}public void sysOut(){ System.out.println("Banana!"); }
}
Is it true that I understand that
myThread.sysOut()
This method will be generated mainly by the flow rather than the flowt1
?
If I'm aware of the right way out of here to trigger a methodsysOut
Not mainly the flow through the interfaceRunnable
and not from classThread
?
-
You can't just take the method in another flow.
You can somehow send a signal to the flow that he understands what he needs and does.public class Main{ public static void main(String[] args) { MyThread myThread = new MyThread(); Thread t1 = new Thread(myThread); t1.start(); myThread.sysOutInThread(); } }
public class MyThread implements Runnable {
public void run(){
synchronized (this) {
wait(); // ждать сигнал
}
sysOut();
}public void sysOut(){ System.out.println("Banana!"); } public void sysOutInThread() { synchronized (this) { notifyAll(); // просигнализировать } }
}
Basic flow - Main
t1.start()
- CategorymyThread.run()
- CategorymyThread.wait()
run()
already implemented in new flow t1
The t1 flow is hanging inwait()
Basic flow - Main
myThread.sysOutInThread()
- CategorymyThread.notifyAll()
It's mostly flow.notifyAll()
sends a signal to the expected flow t1wait()
in the flow of t1 receives a signal and the flow finally comes out ofwait()
and immediately acceptedsysOut()
♪
Everything is done in the flow of t1.The t1 flow is stopped. You can fix it.
run()
Then there's gonna be a signal will be waiting again.sysOut()
And so far as infinity.