Alias Posted January 5, 2021 Share Posted January 5, 2021 public class TEST { public static void main(String[] args) throws InterruptedException { //create our something object that you need to get info from final Something something = new Something(); //create a thread and pass the runnable subclass though as a parameter //so the thread knows what it's job is final Thread thread = new Thread(something); //start the thread thread.start(); //synchronized block with the target of the thread we will be waiting on synchronized (thread) { System.out.println("Entering synchronized block"); //telling the main thread we are waiting on the other thread to complete thread.wait(); //providing our result from the something class System.out.println("Thread has been notified"); System.out.println("Calling the result from something..."); System.out.println("Got result: " + something.getResult()); } } } public class Something implements Runnable { private int result; @Override public void run() { // the synchronized block that will execute after wait() was called on this // object synchronized (this) { //just doing the math final int num = 5; final int multiplier = 5; result = num * multiplier; System.out.println("Did math, the answer is: " + result); // notify must be called to notify the main thread that this job is complete and // the other thread can proceed notify(); } } //grabbing the result of whatever info want from this class public int getResult() { return this.result; } } OUTPUT: Entering synchronized block Did math, the answer is: 25 Thread has been notified Calling the result from something... Got result: 25 1 Quote Link to comment Share on other sites More sharing options...
Proto Posted January 5, 2021 Share Posted January 5, 2021 (edited) Good snippet 😄 ps. there is formatting for java code that makes code look nicer in your post 🙂 Edited January 5, 2021 by Proto 1 Quote Link to comment Share on other sites More sharing options...
Sellout Posted January 5, 2021 Share Posted January 5, 2021 nice 1 Quote Link to comment Share on other sites More sharing options...
smile Posted January 6, 2021 Share Posted January 6, 2021 nice :) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.