The JAVA program for "Philosopher Problem"

When I learn the book of "Operating Systems (Design and Implementation)"(written by Andrew S.Tanenbaum), I try to write a program for the "Philosopher Problem" . In the book there is a sample of this problem in C language, and I write it in JAVA. The following is my program, I have tested it. It is correct, but maybe it is not the most efficient way to solve the problem. Can you think out a more efficient program in JAVA to solve this problem?
* Philosopher Eating Problem
* @author mubin
* @version 1.0
public class PhilosopherEating {
//Philosophers' number
private final static int PHER_NUM = 20;
//Philosophers' state
private volatile static int[] pherState = new int[PHER_NUM];
//THINKING
private final static int THINKING = 0;
//HUNGRY
private final static int HUNGRY = 1;
//EATING
private final static int EATING = 2;
//Philosophers thread group
public static Philosopher[] philosophers = new Philosopher[PHER_NUM];
//finish indicator
public volatile static boolean finished =false;
//thread lock
public static Object threadLock = new Object();
public PhilosopherEating() {
* Philosopher class
* @author mubin
* @version 1.0
public static class Philosopher extends Thread{
int pherNo ;
public Philosopher(int no){
this.pherNo = no;
public void run(){
while(!PhilosopherEating.finished){
think();
takeForks(this.pherNo);
eat();
putForks(this.pherNo);
* Thinking
private void think(){
System.out.println("Philosopher"+this.pherNo+"is thinking...");
try {
Thread.sleep( (int)(Math.random()*100));
}catch (Exception ex) {
ex.printStackTrace(System.out);
* Eating
private void eat(){
System.out.println("Philosopher"+this.pherNo+"is eating...");
try {
Thread.sleep( (int)(Math.random()*100));
}catch (Exception ex) {
ex.printStackTrace(System.out);
* Take the fork
private void takeForks(int no){
//System.out.println("takeForks:no:"+no);
synchronized (threadLock) {
pherState[no] = HUNGRY;
testPher(no);
* Put down the fork
private void putForks(int no){
//System.out.println("putForks:no:"+no);
synchronized (threadLock) {
pherState[no] = THINKING;
if( pherState[getLeft()]==HUNGRY ){
philosophers[getLeft()].interrupt();
if( pherState[getRight()]==HUNGRY ){
philosophers[getRight()].interrupt();
* Return the NO. of philosopher who is sitting at the left side of this philosopher
* @return the NO. of the left philosopher
private int getLeft(){
int ret = (pherNo-1)<0? PHER_NUM-1 : (pherNo-1);
return ret;
* Return the NO. of philosopher who is sitting at the right side of this philosopher
* @return the NO. of the right philosopher
private int getRight(){
int ret = (pherNo+1)>=PHER_NUM ? 0 :(pherNo+1);
return ret;
private void testPher(int no){
while(true){
if(pherState[no]==HUNGRY
&&pherState[getLeft()]!=EATING
&&pherState[getRight()]!=EATING) {
pherState[no] = EATING;
//Print and check the philosophers' state
printPher(pherState);
return;
}else{
try {
System.out.println(" Philosopher "+this.pherNo+"is waiting a fork");
threadLock.wait();
}catch (java.lang.InterruptedException ex) {
System.out.println(" Philosopher "+this.pherNo+"is interrupted and woken up to take fork");
//when it is interrupted, do nothing. Just let it continue!
}//end of while(true)
* Print and check the philosophers' state.
* To insure there are no two philosophers sit side by side
* are eating at the same time.
private static void printPher(int[] phers){
System.out.print(" philosophers' state��");
for (int i = 0; i < phers.length; i++) {
System.out.print(" "+phers);
System.out.println("");
for (int i = 0; i < phers.length-1; i++) {
if (phers[i]==EATING && phers[i+1]==EATING){
System.err.println(i+" and "+(i+1)+"two of philosophers sitted side by side are eating at the same time!");
if (phers[0]==EATING && phers[PHER_NUM-1]==EATING){
System.err.println("0 and "+PHER_NUM+"two of philosophers sitted side by side are eating at the same time!");
public static void main(String[] args) {
for (int i = 0; i < PHER_NUM; i++) {
PhilosopherEating.pherState[i] = THINKING;
PhilosopherEating aPhilosopherEating = new PhilosopherEating();
for (int i = 0; i < PHER_NUM; i++) {
philosophers[i] = new Philosopher(i);
philosophers[i].start();
try {
Thread.sleep(30000);
catch (InterruptedException ex) {
ex.printStackTrace(System.out);
//End all the threads of philosophers
PhilosopherEating.finished = true;

this problem is about learning how to use threads/synchronise objects etc, the efficiency of the code isn't really an issue, if that's what you mean. As for the efficiency of the solution, it's very hard to tell how efficient it is, but as long as all the philosphers get to eat there's no problem. I haven't really scrutized your code, but I'm not sure that you have a deadlock free solution: as long as it is possible for all the phils to pick up one fork at the same time there's a problem, and it seems from your code that each philosopher will pick up "his" fork. Again, I could be wrong, I haven't really looked. If you haven't come up with a solution, try drawing it on paper and working it out, or if you're lazy a quick google will probably give you the answer, but I'm pretty sure nobody here will :)

Similar Messages

  • Running the Java program as service.

    Hi,
    I want to create have java program, which runs continously. This would hit check a table in Database for any new records and if there is anything it would post a message to another service. It would keep track of how many messages were posted and how many were completed at any point of time.I should have the ability to stop this service. When a stop sequence is initiated, it should wait till all the messages are processed and shutdown. I am looking for inputs on how to invoke the java program as service and the second part (stopping the service). I dont want to Java wrapper service or commons daemon api. I am on JDK 1.4.2
    Thanks in Advance.
    Regards,
    Arul.

    Do you want to write a daemon? I dont think you can do it without some explicit OS support..
    Well, lemme know if you find a way

  • How can i  apply this  java program for  a jsp page?

    import java.io.*;
    import java.util.*;
    public class FileProcessing
      //create a vector container  for the input variables
         Vector variables = new Vector();
      //create a vector container for the constants
         Vector constants = new Vector();
      /*create a string expression container for the equation
         as read from the file */
         String expression = " ";
      //create double result container for the final result
         double result = 0;
         public boolean processFile(String filename,String delim)
          //index for values vector
              int num_values = 0;
          //index for constants vector
              int num_constants = 0;
          //current line being read from the external file.
              String curline = " ";
          //start reading from the external file
              try
                   FileReader fr = new FileReader(filename);
                   BufferedReader br = new BufferedReader(fr);
                   while(true)
                        curline = br.readLine();
                        if(curline == null)
                             break;
                    //determine the type of current interaction
                        boolean variable = curline.startsWith("input");
                        boolean constant = curline.startsWith("constant");
                        boolean equation = curline.startsWith("equation");
                        boolean output = curline.startsWith("result");
                   //on input variables
                        if(variable)
                          StringTokenizer st = new StringTokenizer(curline,delim);
                          int num = st.countTokens();
                          int count=0;
                          while(st.hasMoreTokens())
                               String temp = st.nextToken();
                               if(count==1)
                                    byte b[]= new byte[100];
                                    System.out.println(temp);
                                    System.in.read(b);
                                    String inputval = (new String(b)).trim();
                                    variables.add(num_values,inputval);
                                    num_values++;
                               count++;
                        // on constant values
                        if(constant)
                             StringTokenizer st = new StringTokenizer(curline,delim);
                             int num = st.countTokens();
                             int count = 0;
                             while(st.hasMoreTokens())
                                  String temp = st.nextToken();
                                  if(count==1)
                                       byte b[]= new byte[100];
                                       System.out.println(temp);
                                       System.in.read(b);
                                       String cons = (new String(b)).trim();
                                       constants.add(num_constants,cons);
                                       num_constants++;
                                  count++;
                        // on equation
                        if(equation)
                             StringTokenizer st = new StringTokenizer(curline,delim);
                             int num = st.countTokens();
                             int count = 0;
                             while(st.hasMoreTokens())
                                  String temp = st.nextToken();
                                  if(count==2)
                                       this.expression = temp;
                                  count++;
              // now we are ready to evaluate the expression
                       if(output)
                          org.nfunk.jep.JEP  myparser= new org.nfunk.jep.JEP();
                          myparser.setAllowAssignment(true);
                          for(int i=1;i<variables.size()+1;i++)
                             String name = "arg"+Integer.toString(i);
                             myparser.addVariable(name,new Double(variables.get(i-1)
                                                .toString()).doubleValue());
                          for(int i=1;i<constants.size()+1;i++)
                               String name = "arg" +Integer.
                                         toString(i+variables.size());
                               myparser.addConstant(name,new Double(constants.get(i-1).toString()));
                   //output is obtained as follows
                          myparser.parseExpression(expression);
                          result = myparser.getValue();
                          System.out.println("Assay value: "+result);
              catch(Exception e)
                   System.out.println(e.toString());
              return true;
         public static void main(String[] args)
              FileProcessing fp = new FileProcessing();
              fp.processFile("input.eqn",":");
    }//my text file name is: "input.eqn" (given below)
    input:Enter Value1:arg1
    input:Enter Value2:arg2
    input:Enter Value3:arg3
    constant:arg4
    constant:arg5
    Equation:arg1+arg2+arg3
    result:

    how can i apply this java program for a jsp pagewhy do you want to do this ?
    Your program reads from a file on the disk and formats based on a patterm.
    Jsp is not intended for such stuff.
    ram.

  • Is Premiere Pro CS3 the right program for me?

    Is Premiere Pro CS3 the right program for me?
    I am looking for a program that I can:
    Import files that were recorded on a DVR (mp4 format)
    Take two files placed next to each other on one screen and record a DVD
    | | | |
    | | | |
    | image one | | image two |
    | | | |
    |______________| |_______________|
    Also export the files to other file formats, AVi, MOV

    Dave,
    Premiere can do a PiP, Picture in Picture (basically, your PiP is one half of the frame), BUT your MP4 source is not the best to edit, especially with PP. If you had DV-AVI files, Captured in PP from a miniDV (tape) vid-cam, it would do a great job, but so would its little brother Premiere Elements, which wants the same source files as PP.
    I have not used Womble, that Jeff recommends, but think that it has PiP. Ideally, you want to keep any re-compression down to a minimum, as you are already working with compressed MPEG files, and every additional re-compression WILL cause image degredation. Depending on the CODEC used to create your MP4 files, you have probably lost a lot of info already, and when you go to MPEG-2 (DV CODEC), for DVD, you'll loose even more. About the only way that I see you keeping any quality is if your MP4's are coded for Blu-Ray, and you can find a program with Smart Render, leaving them just as they are, allowing you to edit, then burning to a BD. Lot of "if's" in that.
    I'd check out Womble and see if it can do PiP and if it works with MP4. If Jeff recommended it, it's very likely to do that. Juat expect a major quality hit, because you're already compressed the heck out of the image data once, and will have to do it again.
    You could convert your MP4's to DV-AVI with a 3rd party program, Import them into PP, or PE, edit and then burn to DVD - with Encore in PP, or directly from PE. See above for comments on quality hit. It's those source files that are the problem. That format is meant for distribution/viewing and not for editing. The effect, however, is easy as can be. There are many tutorials on how to do it with variations, on the Web, but nearly all NLE programs want better source material to start, if any quality is to be maintained.
    I'd also post on the Premiere Elements forum, as a lot of people there work with less than ideal source files, and might know of good free, or cheap, conversion programs to use. If you have the CODEC on your machine, DigitalMedia Converter can handle the conversion for you, and do it in batch. It's cheap at ~ US$45, and can batch process, but it cannot improve the quality, or get back the data lost in the first compression - nothing can.
    If this is all you want to do, with the above comments on conversion first taken seriously, Premiere Elements will cost about US$100 and do it easily.
    Sorry for the bad news,
    Hunt

  • How to abend the java program -if the condition fails

    Hi
    My program counts the number of headers in the input file and if the condition fails to satisfy the number we expected , it should comeout of the java program . Is their a specific statement to abend the program in java .
    if(columnCount == 5)
    // do all the steps
    else
    //abend the program }
    how to do that .... is it System.exit(1) or anything else
    thanks..
    Edited by: 1sai on Apr 23, 2009 6:52 PM

    BigDaddyLoveHandles wrote:
    It must have been that the [card sorters|http://en.wikipedia.org/wiki/Card_sorter] were making such a ruckus that I didn't hear it. The model 84 -- 2,000 cards a minute? -- d&auml;mn, that's sweet.
    I remember the first time I saw a card sorter in action, thinking it was kind of cool.
    I also think the teacher used it to describe some sorting algorithm, maybe radix sort??
    You've got me thinking, that might be part of the problem with computing today, not enough moving parts. No big tape drives spinning and oscillating. And few if any line printers anymore. Now there's an interesting piece of equipment.

  • What's the standard program for smartform : HR_ECM_CRS

    Hi Friends
    what's the standard program for smartform : HR_ECM_CRS?
    <REMOVED BY MODERATOR>
    Regards,
    Sree
    Edited by: Alvaro Tejada Galindo on Feb 21, 2008 4:14 PM

    hi
    good
    check this link, hope this would help you to solve your problem.
    http://saphelpbykevin.blogspot.com/2006/09/compensation-review-statement-confusion.html
    thanks
    mrutyun^

  • Hey ! At the moment I am creating a eBook, which should contain links to iTunes. Does anyone know, if it is necesary to join the affiliate program for this ?? Cause I don`t want to ;-)

    Hey ! At the moment I am creating a eBook, which should contain links to iTunes.
    Does anyone know, if it is necessary to join the affiliate program for this ?? Cause I don`t want to ;-)

    Hi Bruce,
    I'm getting closer. I actually tried a variety of  expressions, such as "== null" and yours, but the problem persists.
    I am settling on the following, but there is a hangup related to the field that is being looked at for the condition that I will explain in a minute. Here's the script:
    if 
    (ViolationsTable.ViolCorrSection.ViolationsText.DebitVal.isNull || ViolationsTable.ViolCorrSection.ViolationsText.DebitVal.rawValue.length == 0)
    ViolationsTable.ViolCorrSection.instanceManager.removeInstance(parent.parent.index);
    else
    app.alert ("Warning Statement);
    ViolationsTable.ViolCorrSection.instanceManager.removeInstance(parent.parent.index);
    What happens is that, no matter which row in my table I'm in when I click the remove instance button, the script is always looking to the DebitVal field in the first row of the table. So, if the first row is empty, the message box won't appear for the removal of any row in my table. If the first row has a value in DebitVal, then the deletion of any row in the table will trigger the message box.
    I need a way to specify the script to look at the DebitVal field in the row that I am clicking in, without messing up the remove instance command.
    Ideas?
    Dave

  • Need to change the directory using the java program

    hi,
    can anyone give me the code to change the directory in the java program by using the system command.
    as in C where we use the system call system("cd");
    the same way how to do that in java. please help me with that!!!

    Please search the forums for "runtime.exec", there are dozens of examples posted.
    Although this may not do you any good, since changing the os's directory is not likely to change anything you're using in Java. What are you trying to do?

  • TA24002 My 500 GB can't verify nor repair. I have photoshop work that I need to recover. I would like to know which erase option would be the best solution for this problem.

    My 500 GB can't verify nor repair. I have photoshop work that I need to recover. I would like to know what option would be the best solution for this problem?

    You appear to have two issues: 1) a hard drive that is not working properly and 2) files you wish to recover.
    Re 1) you need to answer Kappy's questions.
    Re 2) does the drive load and can you see your photo files? If so can you copy them to another drive?
    Do you not have a backup of the photo files?

  • I have problems in the initiation of the Encore process when opening presents the following error message : "Encore CS6 Cannot Run in Non-Royalty Serialized".... What is the best solution for this problem ?

    Help Me.
    What is the best solution for this problem ?

    Encore is activated when you activate Premiere Pro... so, as Stan asked, how did you install P-Pro?
    Ask for serial number http://forums.adobe.com/thread/1234635 has a FAQ link
    -and a fix for Encore http://forums.adobe.com/thread/1421765?tstart=0 in reply #7
    -plus more Encore http://helpx.adobe.com/encore/kb/cant-write-image-fie-larger1.html

  • How do you globally change the default program for opening photo files?

    I want to adjust my system so that when I double click a photo file, Preview does not automatically launch.  I work in Photoshop all the time and would prefer that it be the default program for pictures.  I have already changed the "when you insert a picture CD" command in CD's & DVD's in System preferences but this does not have any effect on when I double click on a picture file to open it; Preview always launches and opens the picture there.  That automatic opening behavior is fine but I need it to happen in Photoshop.

    Assuming your pictures are all .jpg files: select any .jpg by clicking once on it in the Finder, then press Command+I to Get Info about it. In the Open With: section of the Get Info window, change the preferred application from Preview to Photoshop, then click the Change All button.
    Now any .jpg file that you double-click will open in Photoshop.

  • Making Pages the default program for opening text documents

    How do I make Pages the default program for opening text documents? Every time I open a text doc it launches in TextEdit. This must be an easy fix, but I can't seem to figure it out.

    Select a text document > Menu > File > Info > Open With > Browse into your appliCations folder > iWork > Pages > OK > Change All…+
    Peter

  • How can I change the default program for the external applications editor?

    I have read the on line directions for this and it reads "select a file type in the left pane."   I do not see where this is in the left pane.  All I see in the left pane is "Browser start pages" and a "How do I " Pane.  Nothing with file types.

    Hello,
    Welcome to Adobe Forums.
    In order to change the default program for the external applications editor. Please follow the steps as mentioned below.
    Click on Edit menu then choose preferences.
    Once the preferences dialog box open.
    click on file editors.
    On the Left pane you will find all the file types which you want to edit .
    On the right hand side you will find the editors for that specific file type.
    If you want to add any other application you need to click on + symbol at the top of right pane.
    Select the path of that application which you want to apply.
    clcik on open.
    If you want to make it primay you can click make primary option available at the right hand top. For more detials please check the screenshot below.
    Regards,
    Rajeev

  • How do I make Pages the default program for .doc files?

    How do I make Pages the default program for .doc files without having the need to change the default program for each individual.doc file?

    Navigate to a .doc file.
    Ctrl click the file
    Choose Open with and then go down the list, past pages, to other
    Navigate to pages
    Before you click Open make sure you click the 'Always open with' check box.
    You should be okay.
    You can do a similar think by selecting the file, Choosing File-Get Info
    Then open the Open With Disclosure triangle.
    select pages and then click CHANGE ALL
    Hope this hleps.
    M.

  • After Upgrading Acrobat Reader XI to Acrobat XI Pro the previewer in Outlook and Windows Explorer doesn't work.  I have to set the default program for .pdf's to Acrobat Reader inorder for the previewer to work.

    After Upgrading Acrobat Reader XI to Acrobat XI Pro the previewer in Outlook and Windows Explorer doesn't work.  I have to set the default program for .pdf's to Acrobat Reader in order for the previewer to work.
    Can anyone recommend a solution?

    If I set the default program for viewing PDF as Acrobat XI Pro the a PDF file will open with Acrobat XI Pro, but in Outlook I will get a white screen and the information bubble "This file cannot be previewed because there is no previewer installed for it" and in Windows Explorer I get a white screen in the preview pane.
    My Acrobat version is 11.0.10
    I am running Windows 7 Professional with Service Pack 1
    My Internet Explorer is Version 11.0.9600.17691
    Update Versions 11.0.17 (KB3032359)
    I am running Microsoft Office 2013

Maybe you are looking for