Jump to content

[Snippet] Synchronized threads


Alias

Recommended Posts

 

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

 

  • Like 1
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...