I am trying to implement 2-threads solution using LockOne(Mutually Exclusive) Algorithm. Implementing this algorithm, i am trying work out a thread defining my own lock methods but i am not getting the desired output. When i run the program..all i get as output is "Thread-0 Locked" and "Thread-1 Locked"..Can anyone plz let me know where am i going wrong? my code is given below
public class Main {
static MyLock lock=null;
static int count=0;
public static void main(String[] args) throws InterruptedException {
Thread[] threads=new Thread[2];
threads[0]=new Thread(new MyThread());
threads[1]=new Thread(new MyThread());
lock=new MyLock();
threads[0].start();
threads[1].start();
threads[0].join();
threads[1].join();
System.out.println(count);
}
}
public class MyLock{
private boolean locked=false;
private String current;
public void lock() {
if(!locked){
locked=true;
current=Thread.currentThread().getName();
}
System.out.println(Thread.currentThread().getName()+" locked");
while(locked && current!=Thread.currentThread().getName());
}
public void unlock() {
System.out.println(Thread.currentThread().getName()+" unlocked");
locked=false;
}
}
public class MyThread implements Runnable{
@Override
public void run() {
int i=1;
while(i<=100){
Main.lock.lock();
Main.count++;
Main.lock.unlock();
i++;
}
}
}