0% found this document useful (0 votes)
3 views2 pages

Java Thread Synchronization Example

The document contains a Java program that demonstrates a synchronized counter using multiple threads. It includes a Producer that increments a counter and a Consumer that decrements it, both utilizing a locking mechanism to ensure thread safety. The program measures and prints the time taken for the operations and the final counter value after execution.

Uploaded by

hoangtu112201
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)
3 views2 pages

Java Thread Synchronization Example

The document contains a Java program that demonstrates a synchronized counter using multiple threads. It includes a Producer that increments a counter and a Consumer that decrements it, both utilizing a locking mechanism to ensure thread safety. The program measures and prints the time taken for the operations and the final counter value after execution.

Uploaded by

hoangtu112201
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

# SyncObjTest.

java
import [Link];
import [Link];

public class SyncObjTest {

public static void main(String[] args) {


CounterLock c_lock = new CounterLock();
int inc_num = 10001234;
int dec_num = 10000000;

long start = [Link]();


Thread p = new Thread (new Producer(c_lock, inc_num));
[Link]();

Thread c = new Thread (new Consumer(c_lock, dec_num));


[Link]();
try {
[Link]();
} catch (InterruptedException e) {}

try {
[Link]();
} catch (InterruptedException e) {}
long finish = [Link]();
[Link](inc_num+" inc() calls, "+dec_num+" dec() calls = " +
c_lock.getCount());
[Link]("With-SyncObj time: "+(finish-start)+"ms");
}
}

class Producer implements Runnable{

private CounterLock myCounter;


int num;

public Producer(CounterLock x, int Num) {


[Link]=Num;
[Link] = x;
}

@Override
public void run() {
for (int i = 0; i < num; i++) {
[Link]();
}
}
}

class Consumer implements Runnable{

private CounterLock myCounter;


int num;

public Consumer(CounterLock x, int Num) {


[Link]=Num;
[Link] = x;
}
@Override
public void run() {
for (int i = 0; i < num; i++) {
[Link]();
}
}
}

class CounterLock {

private long count = 0;

public void inc() {


synchronized (this) {
[Link]++;
}
}

public void dec() {


synchronized (this) {
[Link]--;
}
}

public synchronized long getCount() {


synchronized (this) {
return [Link];
}
}
}
Beta
0 / 0
used queries
1

You might also like