package examples; import java.util.concurrent.locks.ReentrantLock; import javax.swing.JProgressBar; public class ProgressLoop extends JProgressBar implements Runnable { private static final long serialVersionUID = 1L; static int sharedValue = 0; public ProgressLoop() { super(0, 100); // start and maximum values } static synchronized int getSharedValue() { return sharedValue; } static synchronized void setSharedValue(int value) { sharedValue = value; } static synchronized void incrementSharedValue() { sharedValue++; } // public void run() { // for (int i = 1; i <= 100; i++) { // setValue(i); // } // } // public void run() { // sleep between steps // for (int i = 1; i <= 100; i++) { // setValue(i); // rest(10*i); // } // } void rest(int milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException ie) { // wake up } } // public void run() { // increment shared value // for (int i = 1; i <= 100; i++) { // int local = getSharedValue(); // setValue(i); // might get switched out by the scheduler // setSharedValue(local+1); // System.out.println(local+1); // rest(10); // } // } static ReentrantLock lock = new ReentrantLock(); // public void run() { // sequentially // lock.lock(); // for (int i = 1; i <= 100; i++) { // int local = getSharedValue(); // setValue(i); // setSharedValue(local+1); // System.out.println(i); // rest(10); // } // lock.unlock(); // } // // public void run() { // concurrently // for (int i = 1; i <= 100; i++) { // lock.lock(); // // begin atomic section // int local = getSharedValue(); // setValue(i); // setSharedValue(local+1); // // end atomic section // lock.unlock(); // System.out.println(i); // rest(10); // } // } // public void run() { // concurrently // for (int i = 1; i <= 100; i++) { // setValue(i); // setSharedValue(getSharedValue()+1); // System.out.println(i); // rest(10); // } // } public void run() { // concurrently for (int i = 1; i <= 100; i++) { setValue(i); incrementSharedValue(); // System.out.println(i); // rest(10); } } }