I am pretty new to Multithreading programming. In my code threads are trying to acquire locks around few lines. The lines work pretty fine for few context switches but then it halts (probably a deadlock).

On the other hand if use `synchronized` block then all works fine.

I've four classes.

**1. PetersonAlgorithm.java**

```
package com.ashish.master;

public class PetersonAlgorithm {

    boolean wantCS[] = {false, false};
    int turn = 1;

    public void requestCS(int i) {
        System.out.println("Lock requested by the thread - " + i);
        wantCS[i] = true;
        turn = 1 - i;
        while(wantCS[1-i] && turn == 1-i);

    }

    public void releaseCS (int i) {
        wantCS[i] = false;
        turn = i - 1;
        System.out.println("Lock released by the thread - " + i);
    }

}

```

If anyone feels that above algorithm is incorrect then let me know, and feel free to make suggestions.

**2. Runner.java**

```
package com.ashish.master;

public class Runner {

    public static Incrementer runnableInstance = new Incrementer();
    public static Thread inc1 = new Thread(runnableInstance, "0");
    public static Thread inc2 = new Thread(runnableInstance, "1");

    public static void main(String args[]) {

        inc1.start();
        inc2.start();

        try{
            inc1.join();
            inc2.join();
        } catch (InterruptedException ex) {
            System.out.println("The threads have been interrupted while waiting for the join ---> " + ex.getMessage());
        }

        System.out.println("The total turns taken by incrementer are ----> " + runnableInstance.turns);

    }

}

```

**3. Incrementer.java** - *If `synchronized` block is used instead of the Peterson algorithm, everything works fine.*

```
package com.ashish.master;

public class Incrementer implements Runnable {

    public long turns = 0;
    public PetersonAlgorithm pa = new PetersonAlgorithm();

    @Override
    public void run() {

        System.out.println("Thread " + this.toString() + "started.....");
        while(true) {
            pa.requestCS(Integer.parseInt(this.toString()));
//          synchronized(this) {
                if(DataStore.data < 1000000) printCriticalSection();
                else break;
//          }
            pa.releaseCS(Integer.parseInt(this.toString()));
        }

    }

    public void printCriticalSection() {
        System.out.println("The value of the number is increased by thread " +
                this.toString() +" to --> " + DataStore.increase());
            turns ++;       
    }

    @Override
    public String toString() {
        return Thread.currentThread().getName();
    }

}

```

**4. DataStore.java** *A class to mock the data source -- simply increase the number*

```
package com.ashish.master;

public class DataStore {

    public static long data = 0L;

    public static long increase() {
        DataStore.data += 1;
        return DataStore.data;
    }

}

```