• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 390
  • Last Modified:

Semaphore better Implementation

Hi!
Any Idea on how to implement the Semaphore below!

public class StundentLists extends Thread {
    Lists listsHH;
    Semaphore sema;

    public StundentLists(Lists b) {
     listsHH = a;
     this.sema = sema;

   }

    public void run () {
    try { sema.semaWait();

   } catch (Exception e) {System.out.println(e);
}
      int total = listsHH.StundentLists();
      System.out.println ("ADD: total =" +  total);
       sema.semaSignal();
    }

  }

Thanks in Advance
0
ZURINET
Asked:
ZURINET
  • 6
  • 6
  • 5
  • +2
3 Solutions
 
zzynxSoftware engineerCommented:
>>    public StundentLists(Lists b) {
>>     listsHH = a;
>>     this.sema = sema;
>>
>>   }

What does
>>     this.sema = sema;
do? What is "sema"?
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
zzynxSoftware engineerCommented:
Or the first link you get when you Google with "java Semaphore":
http://www.javaworld.com/javaworld/javaqa/1999-11/02-qa-semaphore.html

;°)
0
 
ZURINETAuthor Commented:
zzynx
I have a semaphore class that I am calling

 >>    public StundentLists(Lists b) {
>>     listsHH = a;
>>     this.sema = sema;
>>
>>   }

What does
>>     this.sema = sema;
do? What is "sema"?
0
 
zzynxSoftware engineerCommented:
this.sema stands for the Semaphore instance 'sema', member of the StudentLists class,
but what variable is the 2nd "sema"?
Also what is the variable "a" in listsHH = a; ?
0
 
zzynxSoftware engineerCommented:
Neither "sema" nor "a" seems to be parameters of the StudentLists constructor That's what I meant.
0
 
ZURINETAuthor Commented:

Lets put it in another way i have two Threads

  Thread t1 = new Thread(new StundentLists(Lists ));
    Thread t2 = new Thread(new TransferStudnets(2,1,100,Lists));
        t1.start();
          t2.start();

I want to use Semaphore to make the treads execute one after the other
0
 
objectsCommented:
> I want to use Semaphore to make the treads execute one after the other

don't really need a semaphore, you could instead wait until the first finished before starting the second (using join()). Or start up the second at the the end of the first threads run() method.
0
 
objectsCommented:
 Thread t1 = new Thread(new StundentLists(Lists ));
    Thread t2 = new Thread(new TransferStudnets(2,1,100,Lists));
       t1.start();
         t1.join()   // wait for t1 to finish before starting t2
         t2.start();
0
 
ZURINETAuthor Commented:
Semaphore is part of the requirement . needed ;-)
0
 
zzynxSoftware engineerCommented:
That's the 4th link when you Google with "java Semaphore" ;°)
0
 
CEHJCommented:
Here's an example using Semaphore:


package concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {

      public static void main(String[] args) {
            new SemaphoreTest().run();

      }

      public void run() {
            Semaphore semaphore = new Semaphore(1);
            List<String> students = new ArrayList<String>();

            final StudentList listSetter = new StudentList(students, semaphore) {
                  public void run() {
                        try {
                              getSemaphore().acquire();
                              //Date startedSending =  new Date();
                              long time =  System.currentTimeMillis();
                              System.out.printf("listSetter started filling list at %tT:%tL\n", time, time);
                              List<String> list = getStudents();
                              for (int i = 0; i <= 3; i++) {
                                    list.add("Student" + i);
                                    Thread.sleep((int) (Math.random() * 2000));
                              }
                              time = System.currentTimeMillis();
                              System.out.printf("listSetter finished filling list at %tT:%tL\n", time, time);
                              getSemaphore().release();
                        } catch (InterruptedException e) {
                              // ignore
                        }
                  }
            };

            final StudentList listReceiver = new StudentList(students, semaphore) {
                  public void run() {
                        try {
                              long time =  System.currentTimeMillis();
                              System.out.printf("listReceiver started waiting for list at %tT:%tL\n", time, time);
                              getSemaphore().acquire();
                              time =  System.currentTimeMillis();
                              System.out.printf("listReceiver finished waiting for list at %tT:%tL\nHere it is:\n%s", time, time, getStudents());
                        } catch (InterruptedException e) {
                              // ignore
                        }
                        
                  }
            };
            new Thread(listSetter).start();
            new Thread(listReceiver).start();
      }

      abstract class StudentList implements Runnable {
            private List<String> students;

            private Semaphore semaphore;

            public StudentList(List<String> students, Semaphore semaphore) {
                  this.students = students;
                  this.semaphore = semaphore;
            }

            public abstract void run();

            public List<String> getStudents() {
                  return students;
            }

            public Semaphore getSemaphore() {
                  return semaphore;
            }

      }

}
0
 
MogalManicCommented:
A semaphore is a COMMON object that both threads use to control flow.  This means both thread need to have the SAME object to wait.  Maybe something like this:
    Semaphore sema=new Semaphore();
    Thread t1 = new Thread(new StundentLists(Lists, sema ));
    Thread t2 = new Thread(new TransferStudnets(2,1,100,Lists, sema));
    t1.start();
    t2.start();

When the threads start, both will call the sema.semaWait(); method.  Depending on how it is implemented, I assume only ONE will actually wait, the other will return immediatly.  Since it is up to the thread scheduler to control thread execution, we have no way of guaranteeing which thread will run first.  Before the thread completes it calls sema.Signal();  which notifies the waiting thread that it is now safe to start.

The semaphore class will need to have these components/features:
   - a boolean to signal that it is has already allowed one thread to start
   - The semaWait()/semaSignal() methods need to be synchronized
     (need to guarantee that only 1 thread is calling each method at a time)
   - The semaWait() method will call this.wait() to stop the thread from continueing
   - The semaSignal method will call this.notify() to signal other thread that it is safe to procede


Think of the semaphore as a traffic signal, when the light is green, it is safe to go, when the light is red, you must stop.

Does this answer your questions?  If not, then post what you have implemented so far for the Semaphore class.
0
 
ZURINETAuthor Commented:
Thanks  MogalManic !!!

you response is on the right track....  Which means I need to implement both sema instance variable, in the  StundentLists class and TransferStudnets class

right ?
0
 
objectsCommented:
Have a look at the link I posted above it discusses a Semaphore class that shows you how to do just that :)
0
 
ZURINETAuthor Commented:
Thanks Objects..

I have checked it out  it helps a little .. my code contains a combination of inner class.. and outer class...

I am almost done in solving the problem with the help of your link and MoganlManic advice ;-)

Thanks
0
 
ZURINETAuthor Commented:
Thanks all for your help....
I think the kick in Programming is when one can solve the problem on its own. with little help from Experts...

Thanks all for contributing.. ;-)


0
 
CEHJCommented:
One way of solving it would simply be to rewrite my example as a non-Java 1.5 app ;-)
0
 
zzynxSoftware engineerCommented:
>> Thanks all for contributing.. ;-)
You're welcome. And never forget how good Google is ;°)
0
 
CEHJCommented:
:-)
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 6
  • 6
  • 5
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now