0% found this document useful (0 votes)
18 views

Mutual Exclusion

This Java code defines a class with a main method that creates multiple threads. The threads increment and decrement shared static variables inside a synchronized block to prevent concurrent access, demonstrating thread synchronization.

Uploaded by

Project Family
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Mutual Exclusion

This Java code defines a class with a main method that creates multiple threads. The threads increment and decrement shared static variables inside a synchronized block to prevent concurrent access, demonstrating thread synchronization.

Uploaded by

Project Family
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.lang.

*;

public class ATEST16 {


public final static int NUMTHREADS = 3;
public static int sharedData = 0;
public static int sharedData2 = 0;
/* Any real java object or array would suit for synchronization */
/* We invent one here since we have two unique data items to synchronize */
/* An in this simple example, they're not in an object */
static class theLock extends Object {
}
static public theLock lockObject = new theLock();

static class theThread extends Thread {


public void run() {
System.out.print("Thread " + getName() + ": Entered\n");
synchronized (lockObject) {
/********** Critical Section *******************/
System.out.print("Thread " + getName() +
": Start critical section, in synchronized block\n");
++sharedData; --sharedData2;
System.out.print("Thread " + getName() +
": End critical section, leave synchronized block\n");
/********** Critical Section *******************/
}
}
}

public static void main(String argv[]) {


theThread threads[] = new theThread[NUMTHREADS];
System.out.print("Entered the testcase\n");

System.out.print("Synchronize to prevent access to shared data\n");


synchronized (lockObject) {

System.out.print("Create/start the thread\n");


for (int i=0; i<NUMTHREADS; ++i) {
threads[i] = new theThread();
threads[i].start();
}

System.out.print("Wait a bit until we're 'done' with the shared data\n");


try {
Thread.sleep(3000);
}
catch (InterruptedException e) {
System.out.print("sleep interrupted\n");
}
System.out.print("Unlock shared data\n");
}

System.out.print("Wait for the threads to complete\n");


for(int i=0; i <NUMTHREADS; ++i) {
threads[i].join();
}
catch (InterruptedException e) {
System.out.print("Join interrupted\n");
}
}

System.out.print("Testcase completed\n");
System.exit(0);
}

You might also like