Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.text.StyleContext;
- import java.sql.SQLOutput;
- import java.util.concurrent.Semaphore;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class Main {
- public static void main(String[] args) throws InterruptedException{
- Incrementor i = new Incrementor();
- Incrementor i2 = new Incrementor();
- MyThread t1 = new MyThread(1, i);
- MyThread t2 = new MyThread(2, i2);
- t1.start();
- t2.start();
- t1.join();
- t2.join();
- System.out.println(i.getCount());
- System.out.println(i2.getCount());
- }
- }
- class MyThread extends Thread {
- int id;
- Incrementor incrementor;
- public MyThread(int _id, Incrementor i) {
- id = _id;
- incrementor = i;
- }
- @Override
- public void run() {
- for(int i = 0; i < 20; i++) {
- // System.out.println("Thread " + id + " " + i);
- incrementor.safe_semaphore_increment();
- }
- }
- }
- class Incrementor {
- private static int count = 0;
- private static Lock lock = new ReentrantLock();
- private static Semaphore semaphore = new Semaphore(2);
- public static void not_safe_increment() {
- ++count;
- try {
- Thread.sleep(5);
- }
- catch (InterruptedException ei) {
- System.out.println(ei);
- }
- }
- public void safe_increment() {
- synchronized (this) {
- count++;
- }
- }
- public static void safe_mutex_increment() {
- lock.lock();
- count++;
- lock.unlock();
- }
- public static void safe_semaphore_increment() {
- try {
- semaphore.acquire();
- count++;
- semaphore.release();
- }
- catch (InterruptedException ie) {
- System.out.println(ie);
- }
- }
- public static int getCount() {
- return count;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement