/*
 * This File is one of the examples from Java Application Development
 * Do not reproduce this code for others or use it in a commercial setting without prior permission from the author.
 */

package tasks;

/**
 *
 * @author Matthew Gregory
 * @website www.matthewgregory-author.com.au
 *
 */
public class SynchronisedTask implements Runnable {
    
    private int i=1;//Explicity initialised to 1
    
    public void run(){
        while (i<=100){
            synchronized(this) {
                //Once a thread has started this block of code it must
                //finish it before any other thread is allowed in.
                System.out.println("Number: "+i //Print out i
                                   +" Processed by: "
                                   +Thread.currentThread().getName());
                i++;//Explicity increment i
            }
//            processData();
            TakeABreak.sleep();
        }
    }
    
    //A synchronized method - note the position of the keyword synchronized
    private synchronized void processData(){
        System.out.println("Number: "+i //Print out i
                                   +" Processed by: "
                                   +Thread.currentThread().getName());
        i++;//Explicity increment i
    }
}
