Java Program Using Threads

Hi there, im really new and have just started programming in Java, i have to create a java program which implement threads. Thread.Wait, thread.start them etc.
Here is the problem, any guidance would be great cheers guys
The manager of a company employs 3 secretaries who are of varying ability, but who all work extremely fast. Secretary A is the most experienced secretary and is capable of typing up a letter once every second. Secretary B is less experienced and is capable of typing up a letter once every 2 seconds. Secretary C is the junior secretary and is capable of typing up a letter once every 4 seconds. When a secretary has typed up a letter he leaves it in the manager?s tray for him to remove and sign. The manager removes and signs a letter from the tray once every 2 seconds. The tray can hold a maximum of 5 letters at a time. The tray?s limited capacity sometimes causes the various workers to be delayed. For example, if the tray is full after a letter has been typed, the secretaries must wait until the manager makes a space available before they can add another letter to the tray. Similarly, the manager must wait for at least one letter to appear in the tray before he can take it out and sign it.
In your program, make use of threads to represent each of the workers (the 3 secretaries and the manager), so that they can work in parallel. You will also need to declare a tray object, and ensure that all communication is properly synchronised to avoid indeterminacy and deadlock. While an office worker is busy typing a letter or signing it, you should send that thread to sleep for the appropriate time period. This can be achieved with a call to:
Thread.sleep(m);
where m is the number of milliseconds for which the thread should suspend.
The output from your program should take the form of a running commentary on the activity taking place in the office. An extract from it might look something like this (though it is up to you how you word this):
Secretary A is ready to type a letter
Secretary A has typed a letter, number now typed = 6
Tray full. Secretary must wait until a letter has been removed before adding another
Secretary C has typed a letter, number now typed = 2
Tray full. Secretary must wait until a letter has been removed before adding another
A letter has been removed from the tray. Tray = 4
The Manager has taken a letter from the tray to sign, number signed = 4
The Manager is ready to sign a letter
     etc
Run your simulation until the secretaries have typed and filed 7 letters each, and the manager has removed and signed all 21 letters.
Thanks again

Then you're probably better off enlisting one-on-one, in-person help from your instructor, a classmate, or a private tutor, or joining a study group. Forums like this are not well-suited to tutoring you from the ground up.
If you're doing multithreaded homework and you don't even know where to start, it sounds like ether the instructor is horrible or you're in over your head, or you just haven't been keeping up with the class.
Good luck.

Similar Messages

  • Unable to connect to ECC system through stand alone JAVA program using JCO.

    Hi All,
    I want to connect to ECC system through standalone JAVA program using jco.while executing my java program it is saying that connection refused.
    I am getting the error as shown below.
    com.sap.mw.jco.JCO$Exception: (102) RFC_ERROR_COMMUNICATION: CMALLC : rc=20 > Co
    nnect from SAP gateway to RFC server failed
    Connect_PM  GWHOST=192.168.10.99, GWSERV=sapgw01, SYSNR=01
    LOCATION    SAP-Gateway on host igm501 / sapgw01
    ERROR       partner '192.168.10.99:sapgw01' not reached
    TIME        Mon Sep  1 15:00:37 2008
    RELEASE     700
    COMPONENT   NI (network interface)
    VERSION     38
    RC          -10
    MODULE      nixxi.cpp
    LINE        2821
    DETAIL      NiPConnect2
    SYSTEM CALL connect
    ERRNO       239
    ERRNO TEXT  Connection refused
    COUNTER     2
            at com.sap.mw.jco.rfc.MiddlewareRFC$Client.nativeConnect(Native Method)
            at com.sap.mw.jco.rfc.MiddlewareRFC$Client.connect(MiddlewareRFC.java:11
    25)
            at com.sap.mw.jco.JCO$Client.connect(JCO.java:3138)
            at JConnector_frmDesk.<init>(JConnector_frmDesk.java:91)
            at JConnector_frmDesk.main(JConnector_frmDesk.java:141)
    I have already configured SAPDP01,SAPGW01 in my services file in windows\system32\drivers\etc\services.
    What else i need to do to connect to ECC system through my JAVA program.Please help me in this regard.
    Regards,
    Ramana.

    Hi !
    Check this to verify that you are correctly using JCO:
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/8e7daa90-0201-0010-9499-cd347ffbbf72
    Try to give in ashost="/H/saprouter/H/sap".
    Regards,
    Matias.

  • Running curl command from a java program using Runtime.getRuntime.exec

    for some reason my curl command does not run when I run it from within my java program and errors out with "https protocol not supported". This same curl command however runs fine from any directory on my red hat linux system.
    To debug the problem, I printed my curl command from the java program before calling Runtime.getRuntime.exec command and then used this o/p to run from the command line and it runs fine.
    I am not using libcurl or anything else, I am running a simple curl command as a command line utility from inside a Java program.
    Any ideas on why this might be happening?

    thanks a lot for your response. The reason why I am using curl is because I need to use certificates and keys to gain access to the internal server. So I use curl "<url> --cert <path to the certificate>" --key "<path to the key>". If you don't mid could you please tell me which version of curl you are using.
    I am using 7.15 in my system.
    Below is the code which errors out.
    public int execCurlCmd(String command)
              String s = null;
              try {
                  // run the Unix "ps -ef" command
                     Process p = Runtime.getRuntime().exec(command);
                     BufferedReader stdInput = new BufferedReader(new
                          InputStreamReader(p.getInputStream()));
                     BufferedReader stdError = new BufferedReader(new
                          InputStreamReader(p.getErrorStream()));
                     // read the output from the command
                     System.out.println("Here is the standard output of the command:\n");
                     while ((s = stdInput.readLine()) != null) {
                         System.out.println(s);
                     // read any errors from the attempted command
                     System.out.println("Here is the standard error of the command (if any):\n");
                     while ((s = stdError.readLine()) != null) {
                         System.out.println(s);
                     return(0);
                 catch (IOException e) {
                     System.out.println("exception happened - here's what I know: ");
                     e.printStackTrace();
                     return(-1);
         }

  • How Can I execute a java program using java code?

    {color:#000000}Hello,
    i am in great trouble someone please help me. i want to execute java program through java code i have compiled the java class using Compiler API now i want to execute this Class file through java code please help me, thanks in advance
    {color}

    Thanks Manko.
    i think my question was not clear enough.. actually i want to run this class using some java code . like any IDE would do i am making a text editor for java, as my term project i have been able to complie the code usign compiler api and it genertaes the class file but now i want to run this class file "THROUGH JAVA CODE" instead of using Java command. I want to achive it programatically. do you have any idea about it.. thanks in advance

  • Compile and run java programs using batch file

    i am using eclipse to run my java programs.How to compile and run those programs using a batch file?

    a) just write a batch file, and add it to the project. When you want to run it, go to a command window and invoke it. (There is probably also a way to invoke it from Eclipse)
    b) if the project is complicated, take a look at ant. Eclispe knows about ant files.

  • Error while loading java program using loadjava

    Hi
    I have oracle 8.1.7 in NT server. When I try to load a java program with load java it gives me the error like this
    Error while resolving class EchoInput
    ORA-00904: invalid column name
    loadjava: 1 errors
    Why this is happening. How can I resolve this. Any help is appreciated
    Thanks
    Santhosh

    You need to install teh jserver component.
    have your dba review this and run all java enabling scripts.
    look for it in the doc as initjvm.sql.

  • Calling an Exe in my java program using its absolute path

    hi folks .
    I m trying to execute an exe, fetching its absolute path for my java program itself .. any suggestions ..i need not to specify the path of exe everytime i execute my java program
    Thanx for ur anticipation.

    see exec() in Runtime

  • How to run a java program using additional jar files

    Hi everyone in the forum,
    i ve created an app using the hFreeChart in eclipse, so i added them as external jar files and tested the program.
    now my problem is that the program should run using a terminal in win and i do not know how can i do to make the command line or the system to find them, i added to the path but i read somtehing about classpath, but i have no idea. if anyone can help?
    thanks in advanced

    Actually, the best way to prepare a program for regular running is to make it an executable jar file, which means adding a manifest file which contains (at least) a Main-class: and a Class-Path: line. Referenced class libraries typically sit in a lib directory next to the java file. Then you can run it using java -jar myprog.jar.
    Failing that create a batch file or link that supplied java with command line parameters including a -classpath=
    Using the class path environment results in too much contention between competing values of it.

  • Doubt in JAVA Programming-Use of GOTO?

    I'm new to JAVA. I found JAVA very strange at first as I was used to much of BASIC programming. Well, keeping all those aside, this is my very 5th program in JAVA. It is a program which inputs a number(from 1-10) and displays it's multiplication table. But when the execution is over, I want the program to repeat itself , in other words, an alternative to 'GOTO' function.
    This is my program:
    // A program to write tables
    import java.io.*;
    public class tables
        public static void main(String args[])throws IOException
            int a=0;//Initializing variables
            System.out.println("LEARN YOUR TABLES.");
            System.out.println("With this program, you can learn tables from 1-10");
            System.out.println("So what are you waiting for? Enter the number you want and hit ENTER");
            InputStreamReader x=new InputStreamReader(System.in);//Input Statement
            BufferedReader in=new BufferedReader(x);
            a=Integer.parseInt(in.readLine());//Store user input in "a"
            switch (a)
                case 1://For 1's tables
                System.out.println("WHAT?!?!?! DONT KNOW TABLES OF 1!!!! ");
                 break;
                case 2://For 2's tables
                int c;//Variables for this case
                for (c=1;c<=10;c++)
                System.out.println(2+" * "+c+" = "+ 2*c);
                break;
                case 3://For 3's tables
                int d=3;
                int e=1;
                do
                    System.out.println(3+" * "+e+" = "+d);
                    e++;
                    d=3*e;
                }while (e<=10);
                break;
                case 4://For 4's tables
                int f,g=1;
                while (g<=10)
                    f=4*g;
                    g++;
                    System.out.println(4 +" * "+g+" = "+f);
                break;
                case 5:
                int h;
                for (h=1;h<=10;h++)
                System.out.println(5+" * "+h+" = "+5*h);
                break;
                default:
                System.out.println("I'm sorry ladies and gentlemen but multiplication");
                System.out.println("for this number is still under construction and I");
                System.out.println("think that it will always be so..............");
    }After the table is executed, I want the program to begin from first. How can that be done?

    Hello dinodig,
    some hints that I hope are helpful:
    1a. Do not put your whole code in your main method, which is only the entry point to your program. I usually call the main class constructor in main(), from where the object oriented programming can start. Put the code in a learningTables() method that you can call every time you want to run that code. 1b. Read on from here!
    2. Go through the [java tutorials|http://download-llnw.oracle.com/javase/tutorial/java/TOC.html] from the beginning to the end. Thatll give you quite a first view of how the language works. Especially read the first chapter, "Object-Oriented Programming Concepts". Seems like a lot, but it really isnt. The ratio of benefit / reading is a really high one.
    3. GOTO is an abomination. It leads to ["spaghetti code"|http://en.wikipedia.org/wiki/Spaghetti_code]. Please dont feel insulted by this, it is a horrible thing. I. e. Im whipping GOTO here, not you. ;-)
    Too slow for sure. Well, Ive got to get my post count up or Mum will beat me again. :-)
    Have fun!

  • How to execute Java programs using Cygwin?

    Ok, so I've installed Cygwin and Netbeans programs. I wrote my program on Netbeans, then tried to use the command javac with Cygwin to compile the main .java file. What next? How do I run the actual program in the Cygwin window?
    Thanks!

    jverd wrote:
    sharkura wrote:
    I thought there was a "native cygwin" version of java available that would, e.g., accept paths like /mnt/c, handle the colon classpath separator, etc. I could be mistaken though. I know there are versions like that for other tools, like perforce and subversion.I'm not sure about a native cygwin port of java, but I use the reference compiler every day, and it handles / just fine (because the bash shell correctly translates it). Are you talking about the file separator? Because that would work fine anyway. Or are you talking about /mnt/c instead of C:? If the latter, I don't recall about Java specifically, but I know I have had problems in both directions in cygwin. For instance, tar can't handle C:, but some existing Windows tools can't handle /mnt/c.
    Ahh, I misunderstood what you were saying. I was talking about a path separator (\ in windows, / in cygwin). The default mount points for drives is, for the version we are using, /cygdrive/c, and that is handled just fine.
    However, it does not handle a colon as a classpath separator if you specify the classpath in the java command. This typically means that the classpath, it written out of the command line, must be "" wrapped (if more than one classpath element exists ... this prevents the bash shell from attempting to split the command at the ;) and must use ; as the path element separator.
    I suppose you could specify the classpath like so, path/element/dir1\;path/element/dir2\;path/element/jar1.jar, without "".Doesn't really matter to me as I use ant to start all my non-trivial programs.As do I. I still write test drivers, and sometimes use nonstandard (wrt our project) classpaths.
    {?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Running a java program using URLClassLoader

    I have been developing text editor for my final project which can compile and run java prorams.
    this is the code that i have written for running the class file that is created after compilation---
    import java.net.*;
    import java.net.URLClassLoader;
    import java.net.URL;
    import java.io.File;
    import java.lang.reflect.*;
    public class runMethod extends ClassLoader{
         public void run(String dir, String f){
              File file = new File(dir);
              File[] files = file.listFiles();
         URL[] urls = new URL[files.length];
              try{
                   URL url = file.toURL();
              }catch(MalformedURLException e) {
         System.out.println("MalformedURLException: " + e.getMessage());
                   ClassLoader loader = new URLClassLoader(urls);
              try{
                        Class clazz = Class.forName(f, true,loader);
                        Method method = clazz.getDeclaredMethod("main", new Class[] { String[].class });
                        method.invoke(null, new Object[] {});
                   } catch (Exception ex) {
                   System.out.println(ex.getMessage());
    But the output it gives me is not the running program but "null". please help me in figuring out what is the problem and why is it not running the class file and giving the output.

    Here a complete example.
    Suppose that your workspace is C:/java/projects/, that your project is called myproject and the build directory is called classes (myproject/classes/)
    create the class MyTargetClass in a package called test1 :
    package test1;
    public class MyTargetClass {
         public static void main(String[] args) {
              System.out.println("Hello from "+MyTargetClass.class.getName());
    }Create the class RunMethod in a package called test2 :
    package test2;
    import java.net.*;
    import java.io.File;
    import java.lang.reflect.*;
    public class RunMethod {
         public void run(String dir, String f) {
              URL[] urls = null;
              try {
                   // Convert the file object to a URL
                   File myDir = new File(dir);
                   URL url = myDir.toURL();
                   urls = new URL[] { url };
              } catch (MalformedURLException e) {
                   e.printStackTrace();
              try {
                   // Create a new class loader with the directory
                   ClassLoader cl = new URLClassLoader(urls);
                   // Load in the class
                   Class clazz = cl.loadClass(f);
                   // Create a new instance of the new class
                   //MyTargetClass= (MyTargetClass) clazz.newInstance();
                   Method main = clazz.getDeclaredMethod("main", new Class[] { String[].class });
                   main.invoke(null, new Object[] { null });
              } catch (Exception e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              new RunMethod().run("C:/java/projects/myproject/classes/", "test1.MyTargetClass");
    }Compile and run the RunMethod class.
    Hope That Helps

  • How to get the erroe message, if i run java program using .bat file

    Hi,
    I have a java file which accepts two inputs as command line argument. I want to make this pgm a tool. So have created a *.bat file which has the following command
    java myprogram arg1 arg2
    I'm gonna share this program with others. So i'll keep the class file and the .bat file in a commaon folder. All the users have to do is, edit the .bat file to give his/her args and run the .bat file. The pbm is, if the user input is not valid, I have put displays in the pgm to show it.
    But if i run thru .bat, I'm not getting the error message or I don't know where it is getting displayed.
    Can anyone help me with this ?
    Thanks,
    Mary

    When i run from the console, I can see the output.
    But, when i double click on the .bat file from the
    folder, it runs fine and i couldn't see the output.
    nullThat's because the error message is printed, and then the console is closed. The message is there but you need to read really really fast :)

  • How to Use native keyword in java programming

    Hi ,
    I am using JDK 1.6.0_11 , and i was trying to create a java program using "native" keyword ,
    i got the sample code for the same from the site : - http://www.javaworld.com/javaworld/javatips/jw-javatip23.html
    But when i type this command " C:\javah -stubs Happy " following error occurs
    " Error: JNI does not require stubs, please refer to the JNI documentation. "
    then typed " c:\javah -jni Happy" without any error .
    After that i wrote a HappyImpl.c as mentioned in the above tutorial
    #include <StubPreamble.h> /* Standard native method stuff. */
    #include "Happy.h" /* Generated earlier. */
    #include &ltstdio.h> /* Standard C IO stuff. */
    void Happy_printText (struct HHappy *this)
    puts ("Happy New Year!!!");
    then it is not compling and error is
    "unable to open included file StubPreamble.h file
    unable to open included file Happy.h file "
    Please help me . i want to use native method , i did exactly the same in tutorial at above link.
    Thanks & Regards
    Mannat

    you do need to know how to use your C compiler... It quite clearly can't find those files which indicates that you didn't tell it where to find them.

  • SOLVED: How To Use LDAP over SSL (no certs) from java program

    Trying to connect to OID from Java program (using Grocery Store demo as a test). Want to use SSL with no server certificate. OID is configured, and ldapsearch -U 1 works.
    Tried using URL with ldaps, or adding SECURITY_PROTOCOL,"ssl". In both case the error is 'simple bind failed'.
    Samples on OTN say this should be possible, but then only have code for the non-ssl connection.
    Posting from others with this same question don't seem to have been answered.
    Message was edited by:
    user590350
    I have found that using ConnectionUtil.getSSLDirCtx() from Oracle will make a no-authentication SSL connection. An example in the sample code would be useful.

    Even with Java APIs, There is a way to talk through SSL without bothering about certificates. It's just that you will have to write some code and make some changes in settings.
    Read following to get further information on the same.
    http://kiranthakkar.blogspot.com/2007/04/dummny-certificate-authentication.html
    I don't know or I won't comment whether it's the right approach or not but it's definitely a work around.
    Thanking You
    Kiran Thakkar

  • Running a java program with eclipse

    Hi,
    I'm trying to run this java program(below) in eclipse..when i go to the 'run' icon inorder to choose the option 'run as' then 'java application' , i have 'none applicable' as the only option available. is it possibly because the program uses threads?
    could someone using eclipse please try to execute this program and let me know if you succeed and how exactly you do it.
    package reseaux;
    import java.io.*;
    import java.net.*;
    import java.util.*;
         public class LeServeur extends Thread{
         Socket socket;
         BufferedReader in;
         PrintWriter out;
         Vector FlowList=new Vector(10);
         public LeServeur(Socket socket)throws IOException{
              this.socket=socket;
              in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              out= new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
         public void run(){
              String s;
              synchronized(FlowList){
                   FlowList.addElement(this);
              try{
                   while(!(s = in.readLine()).equalsIgnoreCase("/quit")){
                        for(int i=0;i<FlowList.size();i++){
                             synchronized(FlowList){
                                  LeServeur monServeur=(LeServeur)FlowList.elementAt(i);
                                  monServeur.out.println(s + "\r");
                                  monServeur.out.flush();
              catch(IOException e){
                   e.printStackTrace();
         finally {
         try {
              in.close();
              out.close();
              socket.close();
         } catch(IOException ioe) {
         } finally {
              synchronized(FlowList) {
              FlowList.removeElement(this);
    thanks

    thanks...
    Infact, i wanted to run the main program called 'Serveur' but it uses 'LeServeur'( the code i sent before') and apparently it gives me an error msg that it doesnot recognise the 'LeServeur'...that's why i was thinking that i should probably first compile the 'LeServeur' so that it can be recognised in the 'Serveur' program.
    here is the 'Serveur' code that uses an instantiation of the LeServeur...
    package reseaux;
    import java.net.*;
    import java.io.*;
    public class Serveur {
              public int port;
              public ServerSocket skt;
              public Socket socket;
         public static void main(String[] args) {
              int port=8975;
              ServerSocket skt=null;
              Socket socket=null;
              try{
                   if(args.length>0)
                        port=Integer.parseInt(args[0]);
              catch(NumberFormatException n){
                   System.out.println("This port is used uniquely for listening");
                   System.exit(0);
              try{
                   skt= new ServerSocket(port);
              while (true){
                   socket =skt.accept();
                   LeServeur flow=new LeServeur();
                   flow.start();
         catch(IOException e){
              e.printStackTrace();
         finally{
              try{
                   skt.close();
              catch(IOException e){
                   e.printStackTrace();
    do you know have any idea why it doesnt recognise the 'LeServeur'?
    ps:they're in the same package
    thanks

Maybe you are looking for

  • Legend Calendar view of VC doesn't work

    Hello, I have created a model which returning start date and end date of planned maintenance dates. I can show these dates in calendar view but when I try to add legend to this calendar not only I am not able to see any legend but also calendar is al

  • CSV link doesn't work with popup created using window.showModalDialog

    From a data maintenance page, I allow users to view an audit trail of changes in a window which pops up using the window.showModalDialog method. In the popup page I have a download to CSV file link. When the link is clicked nothing happens. If I chan

  • TCP/IP communication with remote host

    Hey guys,I wrote a class for TCP/IP communication with remote host.I am trying to use this class in following way:Its not working.One thing I am not sure about if I can give IP address of the machine while creating a socket.Please take a look at my p

  • I'm missing part of a song I downloaded from itunes store. How do I fix this?

    How can I fix a song that is missing the last minute? I downloaded it from iTunes store.

  • Why do I have to touch links twice on my Ipad 1?

    I don't know what's going on or when it happened?  But now I have to touch links twice in order to get things to open on my ipad1.  For example.  I go to a newspaper website, say www.mlive.com.  The first time I touch a link to a news story it just h