So i've found an example of how to use Semaphore and made my code into there for Readers-Writers problem.
What it must do, that it has 1 book, only 1 writer can write a new line there and while he is writing, no1 else can access it. When writing is finished, then 2 readers can read at once.

Here is my code

import java.util.Random;
import java.util.concurrent.*;

public class ThreadSync {
	
	private static ThreadSync thrdsync;
	private static Thread t1, t2, t3, t4, t5;
	private static final Random rand = new Random();
	private static Semaphore sm = new Semaphore(2);
	String text = "Beginning of the Book";
	private void busy() {
        try {
            Thread.sleep(rand.nextInt(1000)+1000);
        } catch (InterruptedException e){}
    }
	
	void write(String sentence)
	{
		System.out.println(Thread.currentThread().getName() +" started to WRITE");
		text += "\n" + sentence;
		System.out.println(text);
		System.out.println("End of Book\n");
		System.out.println(Thread.currentThread().getName() +" finished WRITING");
	}
	
	void read() {		System.out.println("\n"+Thread.currentThread().getName() +" started to READ");
		//System.out.println(text);
		//System.out.println("End of Book\n");
	}
	
	private class Writer implements Runnable {
		ThreadSync ts;
		Writer (String name, ThreadSync ts) {
			super();
			this.ts=ts;
		}
		public void run() {
			while (true) {
				busy();	
				//sm.acquire();
				String new_sentence = new String("\tnew line in Book");
				ts.write(new_sentence);
				//sm.release();
			} // of while
		}
	}
	private class Reader implements Runnable {
		ThreadSync ts;
		Reader (String name, ThreadSync ts) {
			super();
			this.ts=ts;
		}
		public void run() {
			while (true) {
				sm.acquire();
				//System.out.print(t);
				sm.release();
				busy();
				ts.read();
			} // of while
		}
	}


public void startThreads() {
	ThreadSync ts = new ThreadSync();
	t1 = new Thread(new Writer("Writer # 1", ts));
	t2 = new Thread(new Reader("Reader # 1", ts));
	//t3 = new Thread(new Reader("Writer # 2", ts));
	//t4 = new Thread(new Reader("Reader # 2", ts));
	//t5 = new Thread(new Reader("Reader # 3", ts));
	t1.start();
	t2.start();
	//t3.start();
	//t4.start();
	//t5.start();
}
public static void main(
	String [] args) {
	thrdsync = new ThreadSync();
	System.out.println("Lets begin...\n");
	thrdsync.startThreads();
	}
}

Semaphore(int permits)
Creates a Semaphore with the given number of permits and nonfair fairness setting.

as i understand that the number is how many readers can use that that semaphore at once (in my example - 2). But my threads are completely messed up, i just don't get how to fix it.

this is my output, very messy:

Lets begin...

Thread-1 started to READ
Thread-0 started to WRITE
Beginning of the Book
new line in Book
End of Book

Thread-0 finished WRITING

Thread-1 started to READ
Thread-0 started to WRITE
Beginning of the Book
new line in Book
new line in Book
End of Book

Thread-0 finished WRITING

Thread-1 started to READ
Thread-0 started to WRITE
Beginning of the Book
new line in Book
new line in Book
new line in Book
End of Book

Thread-0 finished WRITING

Thread-1 started to READ
Thread-0 started to WRITE
Beginning of the Book
new line in Book
new line in Book
new line in Book
new line in Book
End of Book

Thread-0 finished WRITING

Your code is almost correct; I'v made some little changes:

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ThreadSync {

    private static ThreadSync thrdsync;
    private static Thread t1, t2, t3, t4, t5;
    private static final Random rand = new Random();
    private static Semaphore sm = new Semaphore(2, true);
    String text = "Beginning of the Book";

    private void busy() {
        try {
            Thread.sleep(rand.nextInt(1000) + 1000);
        } catch (InterruptedException e) {
        }
    }

    void write(String sentence) {
        System.out.println(Thread.currentThread().getName() + " started to WRITE");
        text += "\n" + sentence;
        System.out.println(text);
        System.out.println("End of Book\n");
        System.out.println(Thread.currentThread().getName() + " finished WRITING");
    }

    void read() {
        System.out.println("\n" + Thread.currentThread().getName() + " started to READ");
        //System.out.println(text);
        //System.out.println("End of Book\n");
    }

    private class Writer implements Runnable {

        ThreadSync ts;

        Writer(String name, ThreadSync ts) {
            super();
            this.ts = ts;
        }

        public void run() {
            while (true) {

                try {
                    sm.acquire();

                } catch (InterruptedException ex) {
                    Logger.getLogger(ThreadSync.class.getName()).log(Level.SEVERE, null, ex);
                }
                String new_sentence = new String("\tnew line in Book");
                busy();
                ts.write(new_sentence);
                sm.release();
            } // of while
        }
    }

    private class Reader implements Runnable {

        ThreadSync ts;

        Reader(String name, ThreadSync ts) {
            super();
            this.ts = ts;
        }

        public void run() {
            while (true) {

                try {
                    sm.acquire();
                } catch (InterruptedException ex) {
                    Logger.getLogger(ThreadSync.class.getName()).log(Level.SEVERE, null, ex);
                }
                //System.out.print(t);
                busy();

                ts.read();
                sm.release();
            } // of while
        }
    }

    public void startThreads() {
        ThreadSync ts = new ThreadSync();
        t1 = new Thread(new Writer("Writer # 1", ts));
        t2 = new Thread(new Reader("Reader # 1", ts));
        //t3 = new Thread(new Reader("Writer # 2", ts));
        t4 = new Thread(new Reader("Reader # 2", ts));
        //t5 = new Thread(new Reader("Reader # 3", ts));
        t1.start();
        t2.start();
        t4.start();
        //t3.start();
        //t4.start();
        //t5.start();
    }

    public static void main(
            String[] args) {
        thrdsync = new ThreadSync();
        System.out.println("Lets begin...\n");
        thrdsync.startThreads();
    }
}

and I got this output

run:
Lets begin...

Thread-0 started to WRITE
Beginning of the Book
        new line in Book
End of Book

Thread-0 finished WRITING

Thread-1 started to READ

Thread-2 started to READ
Thread-0 started to WRITE
Beginning of the Book
        new line in Book
        new line in Book
End of Book

Thread-0 finished WRITING

Thread-1 started to READ

Thread-2 started to READ
Thread-0 started to WRITE
Beginning of the Book
        new line in Book
        new line in Book
        new line in Book
End of Book

Thread-0 finished WRITING

Thread-1 started to READ

Thread-2 started to READ
Thread-0 started to WRITE
Beginning of the Book
        new line in Book
        new line in Book
        new line in Book
        new line in Book
End of Book

Thread-0 finished WRITING

Thread-1 started to READ

Thread-2 started to READ
BUILD STOPPED (total time: 13 seconds)

Note: there is an infinite loop!

Hope it helps

Edited 4 Years Ago by mike_2000_17: Fixed formatting

This question has already been answered. Start a new discussion instead.