aula04TSincronizacaoII

//java -cp . aula04TSincronizacaoII
class SynchBlock implements Runnable {
// A STRING WHICH CAN BE MODIFIED.
// ACCESS TO BUFFER AIMS AT BEING SYNCHRONIZED
// WITHOUT MODIFYING STRINGBUFFER.
    StringBuffer buffer; //acumulador
    int counter;

    public SynchBlock() {
        buffer = new StringBuffer();
        counter = 1;
    }

    //a thread
    public void run() {
       // { //sem sincronized
        synchronized (buffer) { // sincronização..
            System.out.println("Starting synchronized block [ "+ Thread.currentThread().getName() +"]");
            int tempVariable = counter++; //variavel temp= 0, mas o counter=1

// CREATE MESSAGE TO ADD TO BUFFER, INCLUDING LINE FEED
            String message = "Count value is : " + tempVariable + System.lineSeparator();
            try {
                // SIMULATE TIME NEEDED FOR SOME TASK
                Thread.sleep(100);
            } catch (InterruptedException ie) {
            }
            buffer.append(message);
            System.out.println("... ending synchronized block "+ Thread.currentThread().getName() +"]");
        }
    }
}
//java -cp . aula04TSincronizacaoII
public class aula04TSincronizacaoII {
    public static void main(String args[]) throws Exception {
// CREATE A NEW RUNNABLE INSTANCE
        SynchBlock block = new SynchBlock();
        Thread t1 = new Thread(block);
        Thread t2 = new Thread(block);
        Thread t3 = new Thread(block);
        Thread t4 = new Thread(block);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
// WAIT FOR ALL THREE THREADS TO FINISH
        t1.join();
        t2.join();
        t3.join();
        t4.join();
// COUNT SHOULD APPEAR IN THE CORRECT ORDER
        System.out.println(block.buffer);
    }
}
Tags : ,

0 thoughts on “aula04TSincronizacaoII”

Leave a Reply

Your email address will not be published.

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