aula04TSincronizacao

class Counter {
    private int countValue;

    public Counter() {
        countValue = 0;
    }

    public Counter(int start) {
        countValue = start;
    }

    //public void increaseCount() {
    public synchronized void increaseCount() {
        int count = countValue;
        // SIMULATE SLOW DATA PROCESSING AND MODIFICATION.
        // REMOVE THE SYNCHRONIZED KEYWORD AND SEE WHAT HAPPENS...
        try {
            Thread.sleep(5);
        } catch (InterruptedException ie) {
        }
        count = count + 1;
        countValue = count;

        System.out.println("<" + Thread.currentThread().getName() + " >: cout = " + countValue);
    }

    public synchronized int getCount() {
        return countValue;
    }
}

class CountingThread implements Runnable {
    Counter myCounter;
    int countAmount;

    // CONSTRUCT A COUNTING THREAD TO USE THE SPECIFIED COUNTER
    public CountingThread(Counter counter, int amount) {
        myCounter = counter;
        countAmount = amount;
    }

    public void run() {
         // INCREASE THE COUNTER THE SPECIFIED NUMBER OF TIMES
        for (int i = 1; i <= countAmount; i++) {
            // INCREASE THE COUNTER
            myCounter.increaseCount(); //SYNCHRONIZED METHOD
        }
    }
}

public class aula04TSincronizacao {
    public static void main(String[] args) throws InterruptedException {

        // CREATE A NEW, THREAD-SAFE COUNTER
        Counter c = new Counter();

        // OUR RUNNABLE INSTANCE WILL INCREASE THE COUNTER
        // TEN TIMES, FOR EACH THREAD THAT RUNS IT
        Runnable runner = new CountingThread(c, 10);
        System.out.println("Starting counting threads");
        Thread t1 = new Thread(runner);
        Thread t2 = new Thread(runner);
        Thread t3 = new Thread(runner);
        t1.start();
        t2.start();
        t3.start();

        // WAIT FOR ALL THREE THREADS TO FINISH
        t1.join();
        t2.join();
        t3.join();

        //aguardo que as threads terminem
        System.out.println("Counter value is " + c.getCount());
    }
}
Tags : ,

0 thoughts on “aula04TSincronizacao”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.