Page 167 - CTS - CSA TP - Volume 2
P. 167

COMPUTER SOFTWARE APPLICATION - CITS



           EXERCISE 105 : Test multithreading with and without

                                        synchronization


            Objectives

           At the end of this exercise you shall be able to
           •  know the multithreading with and without synchronization
           •  develop Java programs using  multithreading with and without synchronization.

           Requirements

           Tools/Materials
           •  PC / laptop with windows OS
           •   SDK software
           •  Test editor (Visual studio/ subline/ notepad)


           Procedure

           //multithreading with and without synchronization
           class CounterWithSync {
               private int count = 0;



               public synchronized void increment() {
                   for (int i = 0; i < 5; i++) {
                       int currentValue = count;
                       System.out.println(Thread.currentThread().getName() + “ - Before Increment: “ + currentValue);

                       count = currentValue + 1;
                       System.out.println(Thread.currentThread().getName() + “ - After Increment: “ + count);
                   }
               }

           }
           class IncrementThreadWithSync extends Thread {
               private CounterWithSync counter;
               public IncrementThreadWithSync(CounterWithSync counter) {
                   this.counter = counter;
               }

               public void run() {
                   counter.increment();
               }
           }

           public class MultithreadingWithSyncExample {
           public static void main(String[] args) {





                                                           152
   162   163   164   165   166   167   168   169   170   171   172