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 flow t1 ?
    If I'm aware of the right way out of here to trigger a method sysOut Not mainly the flow through the interface Runnableand not from class Thread ?


  • QA Engineer

    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() - Category myThread.run() - Category myThread.wait()
    run() already implemented in new flow t1
    The t1 flow is hanging in wait()

    Basic flow - Main myThread.sysOutInThread() - Category myThread.notifyAll()
    It's mostly flow.
    notifyAll() sends a signal to the expected flow t1

    wait() in the flow of t1 receives a signal and the flow finally comes out of wait() and immediately accepted sysOut()
    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.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2