Plzzz write prog to this simple java threads question

Write a program in C to create four processes. The original processes creates
two children before it prints out "PARENT". The children processes print
"CHILD1" and "CHILD2" respectively. The first child process creates a child
process that prints out "GRANDCHILD".
Note: The output must be guaranteed to print out in the following order each
time it is executed:
GRANDCHILD
CHILD2
CHILD1
PARENT
a. Write the program using C or C++ and forks to create the children processes.
b. Write a second program using Java and Threads for the children processes.
The output statements for CHILD1, CHILD2 and GRANDCHILD must come from print
statements in the run method of the thread.

Most people here will not do your homework for you. If you post a reasonable question that shows you've made some effort, and what the results of that effort were, and provides details about what parts you're having trouble with, then somebody will probably provide guidance so that [you can complete the work.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • What's wrong with this simple java file

    I am learning java input methods. When I tried to compile the below simple java file, there were two errors.
    import java.io.*;
    public class MainClass {
       public static void main(String[] args)  {
        Console console = System.console();
        String user = console.readLine("user: ");
        System.out.println(user);
    }The compiler errors:
    h:\java\MainClass.java:5: cannot resolve symbol
    symbol : class Console
    location: class MainClass
    Console console = System.console();
    ^
    h:\java\MainClass.java:5: cannot resolve symbol
    symbol : method console ()
    location: class java.lang.System
    Console console = System.console();
    ^
    2 errors
    Could anyone take a look and shed some lights on this?

    I have changed to "import java.io.Console;" but this below errors:
    h:\java\MainClass.java:1: cannot resolve symbol
    symbol : class Console
    location: package io
    import java.io.Console;
    ^
    h:\java\MainClass.java:5: cannot resolve symbol
    symbol : class Console
    location: class MainClass
    Console console = System.console();
    ^
    h:\java\MainClass.java:5: cannot resolve symbol
    symbol : method console ()
    location: class java.lang.System
    Console console = System.console();
    ^
    3 errors
    -----------

  • How to write JDBC code in a java thread? for network programming

    Hii guys, i am new to java network programming. I developed small swing application for stock controlling in a shop, so i need to run the database in a server. i try the peer to peer scenario, but the response is too late and the application get stuck. there i wl put my data base java class
    please help me for this, how can i change this java class to networked JDBC
    import com.mysql.jdbc.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class ConnectionSet {
    private String severIp = "localhost";
    private String severPort = "3306";
    private String userName = "root";
    private String password = "123";
    private ResultSet rs;
    public void setSeverIp(String Ip) {
    severIp = Ip;
    public void setSeverPort(String Port) {
    severPort = Port;
    public void SetUserName(String Name) {
    userName = Name;
    public void setPassword(String passWord) {
    password = passWord;
    public ResultSet getResult(String url) throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection cc = (Connection) DriverManager.getConnection("jdbc:mysql://" + getSeverIp() + ":" + getSeverPort() + "/suriyalanka", getUserName(), getPassword());
    Statement s = cc.createStatement();
    rs = s.executeQuery(url);
    // java.sql.ResultSet rs = (ResultSet) DriverManager.getConnection("jdbc:mysql://"+getSeverIp()+":"+getSeverPort()+"/suriyalanka",getUserName(), getPassword()).createStatement().executeQuery(url);
    return rs;
    public Connection getConnection() throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection cc = (Connection) DriverManager.getConnection("jdbc:mysql://" + getSeverIp() + ":" + getSeverPort() + "/suriyalanka", getUserName(), getPassword());
    return cc;
    public void setResult(String url) throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection cc = (Connection) DriverManager.getConnection("jdbc:mysql://" + getSeverIp() + ":" + getSeverPort() + "/suriyalanka", getUserName(), getPassword());
    Statement s = (Statement) cc.createStatement();
    s.executeUpdate(url);
    public String getSeverIp() {
    return severIp;
    public String getSeverPort() {
    return severPort;
    public String getUserName() {
    return userName;
    public String getPassword() {
    return password;
    please help me for this, how can i change this java class to networked JDBC
    Edited by: 798670 on Sep 29, 2010 6:04 AM

    Have you verified that your mysql allows network connections?
    In order to allow network connections you have to comment or remove line "skip-networking" in my.ini(windows) or my.cnf(unix) configuration files of your mysql instance.
    Or if you have the mysql administrator installed
    MySQL Administrator / Startup Variables / Disable networking (uncheck)
    By!

  • Simple java architecture question

    This should be a simple question to answer but I haven't been able to find a good answer.
    I have an application that establishes a network connection with a server and registers event listeners on that connection.
    What I want to do is find a way without a busy-wait/while loop to keep the main() thread running so that the listeners can do their job.
    Here is a sample of what I've got:
    public static void main(String[] args)
    SomeConnection conn1 = null;
    try
    conn1 = new SomeConnection("someaddress");
    TrafficManager tm = conn1.getTraffictManager();
    TrafficHandler th = tm.createTraffichandler(new MessageListener()
                        public void processMessage(Message message)
                             System.out.println("Received: " + message.toString());
         catch (Exception e)
              e.printStackTrace(System.out);
         conn1.disconnect();
    The problem is that the application doesn't stay running to respond to traffic coming across the connection.
    Any guidance would be appreciated.
    Thanks

    Well, what is the job of the MessageListener if it isn't to listen for messages? And apparently it isn't doing that because your application terminates.
    Bear in mind that I don't have any idea how any of those four classes work, or even how they are supposed to work. So let me just quote this line from the API documentation of the Thread class which says when your application will terminate:
    "All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method."
    That must be the case in your application.

  • Simple Java Coding Question

    I know this is a simple question, but I can't search for the answer to this because it involves syntax that Google and the like don't seem to search for..
    I am trying to figure out some Java code that I have found. I would like to know what:
    a[--i] and a[++j] mean.
    My first thought was that they meant to look at the position in the array one less (or more) than i (j). But that doesn't seem to be the case. A is an array of Strings, if that matters...
    Thanks for you help.

    muiajc wrote:
    I know this is a simple question, but I can't search for the answer to this because it involves syntax that Google and the like don't seem to search for..
    I am trying to figure out some Java code that I have found. I would like to know what:
    a[--i] and a[++j] mean.
    It mean increase/decrease the int i/j by 1. This is done before it gets you the value of a[]. for example if i=5 and you said a[--i] it is really a[4] and i is now equal to 4;

  • Simple Java EJB question.

    When it comes to EJB v3 Remote and Local interfaces,
    (With JBoss EJB Container Software in mind, for this question,)
    -Does the Remote interface for the EJB include method signatures from the Bean class
    -that are to be seen
    -that are to be hidden?
    -Does the Local interface for the EJB include method signatures from the Bean class
    -that are to be seen
    -that are to be hidden?
    Which is which for
    -EJB 2.1 ?
    -EJB 3.x ?
    - is EJB 3.x reverse compatible in that it allows use of the javax.ejb.* interfaces,
    and would accept a EJB 2.1 approach, or does it force one to use Annotations
    exclusively?
    Edited by: Zac1234 on Jul 21, 2010 5:21 PM

    muiajc wrote:
    I know this is a simple question, but I can't search for the answer to this because it involves syntax that Google and the like don't seem to search for..
    I am trying to figure out some Java code that I have found. I would like to know what:
    a[--i] and a[++j] mean.
    It mean increase/decrease the int i/j by 1. This is done before it gets you the value of a[]. for example if i=5 and you said a[--i] it is really a[4] and i is now equal to 4;

  • Simple Java Array Question

    // This is how I was taught to make a simple array. You have to define the size first.
    String [] test1 = new String[4];
    test1[0] = "1";
    test1[1] = "2";
    test1[2] = "3";
    test1[3] = "4";
    out.println(test1[0]);
    out.println(test1[1]);
    out.println(test1[2]);
    out.println(test1[3]);
    //If the size is not defined in this second example, why does it still work?
    String [] test2 = {"1","2","3","4"};
    out.println(test2[0]);
    out.println(test2[1]);
    out.println(test2[2]);
    out.println(test2[3]);
    They both produce the same results.

    // This is how I was taught to make a simple array.
    You have to define the size first.
    String [] test1 = new String[4];
    test1[0] = "1";
    test1[1] = "2";
    test1[2] = "3";
    test1[3] = "4";
    out.println(test1[0]);
    out.println(test1[1]);
    out.println(test1[2]);
    out.println(test1[3]);
    //If the size is not defined in this second example,
    why does it still work?
    String [] test2 = {"1","2","3","4"};
    out.println(test2[0]);
    out.println(test2[1]);
    out.println(test2[2]);
    out.println(test2[3]);
    They both produce the same results.Umm..the size is just as well defined in your second as in your first...it is a four element array.
    The second way is akin to the first...also
    String[] s = new String[]{"Hello","I","contain","five","elements"};
    System.out.println(s[5]); Will compile..you will get a run-time ArrayIndexOutOfBoundsException (it is a 5 element array, 0-4, but java will not assume that the variable s is not changed between those two lines of code)..
    Array index/boundary checking is done at run-time, not compile-time.
    In fact:
    String[] s;
    //let's say up in the program
    //and
    public void printS(int i)
    System.out.println(s);
    Will also compile...and if something else happens to set s as a 10 element String array:
    printS(9);would work
    ~David

  • Simple EVENT & THREAD question.

    Hello,
    Let's say I create a thread from the main one... This thread is supposed to do some work while the main one is waiting for the signal that the work is done... After the signal is received by the main thread it can continue to run...
    How this could be done in Java ? I'm looking for things that are similar to WaitForSingleObject(...) and SetEvent(...) in Windows...

    So you want to fire off a Thread, wait for it to do something, and then continue.
    In Java, you'd start off down this road using wait() and notify(), as Tolmak says.
    For example,
    public class Test {
        public static void main(String[] args) {
            System.out.println("Starting Worker thread...");
            Worker w = new Worker();
            Thread t = new Thread(w);
            synchronized(w) {
                t.start();
                try {
                    System.out.println("Waiting for Worker Thread to complete...");
                    w.wait();
                } catch (InterruptedException ignore) {}
            System.out.println("Worker Thread finished. All done!");
        public static class Worker implements Runnable {
            public void run() {
                System.out.println("Worker thread is doing something...");
                try {
                    Thread.sleep(5000L);
                } catch (InterruptedException ignore) {}
                System.out.println("All done. Notifying Main...");
                synchronized(this) {
                    this.notify();
    }Does this get you closer to where you want to be?

  • Simple Java regex question

    I have a file with set of Name:Value pairs
    e.g
    Action1:fail
    Action2:pass
    Action3:fred
    Using regex package I Want to get value of Name "Action1"
    I have tried diff things but I cannot figure out how I can do it. I can find Action1: is present or not but dont know how I can get value associated with it.
    I have tried:
    Pattern pattern = Pattern.compile("Action1");
    CharSequence charSequence = CharSequenceFromFile(fileName); // method retuning charsq from a file
    Matcher matcher = pattern.matcher(charSequence);
    if(matcher.find()){
         int start = matcher.end(0);
         System.out.println("matcher.group(0)"+ matcher.group(0));
    how I can get value associated with specific tag?
    thanks
    anmol

    read the data from the text file on a line basis and you can do:
    String line //get this somehow
    String[] keyPair = line.split(":")g
    System.out.println(keyPair[0]); //your name
    System.out.println(keyPair[1]); //your valueor if you've got the text file in one big string:
    String pattern = "(\\a*):(\\a*)$"; //{alpha}:{alpha}newline //?
    //then
    //do some things with match objects
    //look in the API at java.util.regex

  • Simple Java Sound Question...

    Can I draw waveforms while capturing data? If yes, how. If no, why.
    Thanks. I need the answer ASAP, please help.

    Hi nfactorial,
    Can I draw waveforms while capturing data?If you would like to do that in Java you would need to know about how to use the Java language in general and especially about the Java Sound and Java2D APIs.
    If yes, how.It would be too much to explain to answer such a general question. A general answer is, you need to use the Java Sound API to capture the data for which a waveform should be drawn. The Sound API delivers data as a stream of bytes typically encoded in pulse coded modulation (PCM) format. The data stream has digital samples each representing a level of sound pressure for a certain point in time. The stream of samples in the amplitude/time domain need to be transformed to a spectrum of samples in the amplitude/frequency domain, i.e. a number of PCM samples need to be mapped to the frequencies that should be displayed. This is done with the fast fourier transformation algorithm. Each set of amplitude/frequency values can then be displayed as a waveform by using some line drawing logic. The entire process would need to run constantly, i.e. as bytes are received from the sound data stream transformation and drawing is triggered.
    Related readings:
    Java Tutorial
    http://java.sun.com/docs/books/tutorial/
    Java Sound Documentation
    http://java.sun.com/j2se/1.5.0/docs/guide/sound/index.html
    Java Sound API Programmer's Guide
    http://java.sun.com/j2se/1.5.0/docs/guide/sound/programmer_guide/contents.html
    Java Sound Resources
    http.//www.jsresources.org
    Java 2D Graphics Tutorial
    http://java.sun.com/docs/books/tutorial/2d/index.html
    Wikipedia on fast fourier transformation
    http://en.wikipedia.org/wiki/Fast_fourier_transform
    HTH
    Ulrich

  • Simple java pgm - question

    Hallo,
    to the following pgm I had question:
    static void printPrimes (int max) (= wavy bracket;
    boolean(should be angular brackets) sieve = new booolean (angular br max+1
    angular br)
    int i,j;
    for (i=2; i = max;i++)sieve(angluarbr i angular br)= true
    i= 2
    while (i= <= max;) (=wavy bracket Out.println (i+ " "); // is prime
    for (j=i; j <= j+i) sieve(angular br j angularb.) = false;
    while (i <= maxAmpersandAmpersand !sieve (angular br angular br)I++;
    ) wavy br ) wavy br.
    I hope this is still kind of readable.
    Q's are:
    after the first "for" there is a new i=2, which seems to staty at 2 all the time; the following while does not change this value ( the beginning for i++ does not change this) and so seems to print 2 at all times (??)
    then the inner loop seems to count up all the doubbles of the new prime number and thrwoes it out as false at the end of it;
    the i values (increased with i++ seemsto refere at all times to the unit numbers and only indirect to the un it values, which are written/ assigned to it (??)
    I seem to wonder how the pgm can print out anythings else the 2's.
    I would appreciate any help to that.
    ml
    griz

    I hope this is still kind of readable.No, it's not. http://forum.java.sun.com/help.jspa?sec=formatting
    Why are you omitting the braces and brackets? And why don't you type "program"? Aren't we worth the additional time it takes?
    Q's are:
    after the first "for" there is a new i=2, which
    seems to staty at 2 all the time; the following
    while does not change this value Why should it? You don't tell it to.
    ( the beginning for
    i++ does not change this)It does. It just gets re-set to 2 after the for loop-
    and so seems to print 2 at
    all times (??)Yeah. What else?
    then the inner loop seems to count up all the
    doubbles of the new prime number and thrwoes it out
    as false at the end of it; That part is definitely unreadable.

  • Problem with getNodeValue() - simple Java XPath question

    I am trying to extract the node values from a XML file:
    <root>
      <frame>
         <boxes>
           <box>
              <spec>22</spec>
              <spec>2222</spec>
           </box>
           <box>
              <spec id="BA" value="short"/>
              <spec id="BB" value="thin"/>
              <spec id="BC" value="black"/>
              <spec id="BD" value="full"/>
              <spec id="BE" value="7"/>
              <spec id="BF" value="deactive"/>
           </box>                
         </boxes>
         <circles>
           <circle id="CA" value="blue"/>
           <circle id="CB" value="green"/>
         </circles>
      </frame>
    </root>I use this code:
             XPathFactory factory = XPathFactory.newInstance();
             XPath xpath = factory.newXPath();
             XPathExpression xPathExpression = xpath.compile("/root/frame/boxes/box/spec");            
             Object result = xPathExpression.evaluate(doc, XPathConstants.NODESET);
             NodeList nodes = (NodeList) result;
             for (int i = 0; i < nodes.getLength(); i++) {
                 System.out.println(nodes.item(i).getNodeValue());
             }But only:
    null
    null
    null
    null
    null
    null
    null
    null
    get printed. I would have assumed:
    22
    2222
    null
    null
    null
    null
    null
    null
    since the two first spec nodes contains the above numbers. Any ideas?

    change this:
    XPathExpression xPathExpression = xpath.compile("/root/frame/boxes/box/spec");to this:
    XPathExpression xPathExpression = xpath.compile("/root/frame/boxes/box/spec/text()");Need to xpath all the way down to the text of the node.
    You could use
    System.out.println(nodes.item(i).getTextContent());with your current xpath but if the spec node has children, these will also be included in the output.

  • Simple Java SDK question for server group assignment

    I have a snippet of code below in which I am trying to apply the setProcessingServerGroup() and setProcessingServerGroupChoice() methods to my report object. My question should be relatively simple: I believe I need to cast(?) my iObject report object to iProcessingServerGroupInfo per the API in order to use the setProcessingServerGroup() and setProcessingServerGroupChoice() methods, but I'm not sure how to do so.
    Can someone please advise how to cast my iObject to iProcessingServerGroupInfo?
    Thanks in advance...
    Code:
    IInfoObject iObject = (IInfoObject) childReports.get(i); 
    int sgID_view = Integer.parseInt(serverGroupID_view);
    int sgPref_view = Integer.parseInt(serverGroupPref_view);
    !!!!!  CONVERSION / CAST NEEDED HERE !!!!!
    iProcessingServerGroupInfo.setProcessingServerGroup(sgID_view);
    iProcessingServerGroupInfo.setProcessingServerGroupChoice(sgPref_view);

    To followup, I've been able to cast to IShedulingInfo in order to use the setServerGroup() and setServerGroupChoice() methods successfully:
    IInfoObject iObject = (IInfoObject) iObjects.get(i);    
    ISchedulingInfo iSchedulingInfo = iObject.getSchedulingInfo();
    iSchedulingInfo.setServerGroup(427);
    iSchedulingInfo.setServerGroupChoice(2);
    But I don't know how to perform the cast to be able to access the setProcessingServerGroup(), sterProcessingServerGroupChoice() methods.
    Any help appreciated.
    Thanks!

  • Java Threads Problem

    Hi, I am trying to write a simple java threads program where in one thread reads a file and another thread writes the data into a second file....
    Here is my code, although i think i am correct, my program still runs in a sequential fashion help help help!!!
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    class MyThread extends Thread{
    private int a;
    private int c;
    FileInputStream in;
    FileOutputStream out;
    public MyThread(int a){
    this.a = a;
    public void run(){
    if(this.a==5)
         try {
         in = new FileInputStream("Britney.txt");
    } catch (FileNotFoundException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
    try {
         while((c=in.read())!=-1)
              a = (char) c;
              System.out.println(a);
    catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
    if(this.a==10)
         try {
              out = new FileOutputStream("romi.txt");
         } catch (FileNotFoundException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
         for(int i = 0;i<50;i++)
              try {
                   System.out.println(c);
                   out.write(c);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    class MainMyThread{
    public static void main(String args[]){
    MyThread thr1, thr2;
    thr1 = new MyThread(5);
    thr2 = new MyThread(10);
    thr1.start();
    thr2.start();
    }

    Encephalopathic wrote:
    malcolmmc wrote:
    ... Chances of getting any kind of reply except "me too" can be pretty remote. ....there's actually a better chance of getting a reply on a general forum like this one, ....Can't you just post in both the narrow and the general forum, but include links one to the other in each thread? Or is that against the forum rules/etiquette? Most people here are ok with a crosspost IF those links are included.
    I would also ask that the OP designate one of those threads as the real discussion thread and just direct folks there from the other threads, so that we have one coherent discussion. If he does that, there's no problem with trying to reach out to as broad an audience as possible.
    I would figure that if the poster were upfront about what they are doing, folks wouldn't mind, but I could be wrong.I think that's generally the case. As long as the discussion is confined to one thread (and pointed there from the crossposts) or at the very least all the participants can see all the discussions, I think most people don't have a problem with it. It's when we waste our time answering when he's already got the answer elsewhere that's annoying.

  • Problem with very simple 2 threads java application

    Hi,
    As fa as i'm concerned this is a thread licecycle:
    1. thread created: it is dead.
    2. thread started: it is now alive.
    3. thread executes its run method: it is alive during this method.
    4. after thread finishes its run method: it is dead.
    No I have simple JUnit code:
    public void testThreads() throws Exception {
    WorkTest work = new WorkTest() {
    public void release() {
    // TODO Auto-generated method stub
    public void run() {
    for (int i=0;i<1000;i++){
    log.debug(i+":11111111111");
    //System.out.println(i+":11111111111");
    WorkTest work2 = new WorkTest() {
    public void release() {
    // TODO Auto-generated method stub
    public void run() {
    for (int i=0;i<1000;i++){
    log.debug(i+":22222222222");
    Thread workerThread = new Thread(work);
    Thread workerThread2 = new Thread(work2);
    workerThread.start();
    //workerThread.join();
    workerThread2.start();
    //workerThread2.join();
    And
    public interface WorkTest extends Runnable {
    public abstract void release();
    And that's it..
    On the console I see 999 iterations of both threads only if i uncomment
    //workerThread.join();
    //workerThread2.join();
    In other case I see random number of iterations - JUNIT finishes and Thread1 made 54 and Thread2 233 iterations - the numbers are different every time i start the JUnit..
    What I want? Not to wait until the first one finishes - I want them to start at the same time and they must FINISH their tasks...
    Please help me asap :(

    This is very simple... Look at your code:
    workerThread.start();
    workerThread.join();
    workerThread2.start();
    workerThread2.join();What are you doing here? You start the first thread, then you call join(), which waits until it finishes. Then after it's finished, you start the second thread and wait until it finishes. You should simply do this:
    workerThread.start();
    workerThread2.start();
    workerThread.join();
    workerThread2.join();I.e., you start the 2 threads and then you wait (first for the first one, then for the second one).

Maybe you are looking for

  • Creative Zen 8gb Blacko

    My creative?zen 8Gb mp3 player abruptly shut down leaving a black screen but the power on, and has continued to do so for nearly a month now, I have Formated my player with no results, it would appear the machine has powered down but the battery ligh

  • SCOM SQL MP 6.4.1.0 - Alert CPUUsagePercent2008DataSource.ps1

    Hi Everyone, Can anyone please help me with the following issue: Forced to terminate the following PowerShell script because it ran past the configured timeout 200 seconds. This alert is showing for the following script(s): CPUUsagePercentDataSource.

  • Error in second local currency

    Good evening, we have a problem in our system. We changed the country of the company for some problem in payment. The change effected on the second local currency so we ripristinate the originale country. In particular we have modified from IT to EG

  • SAPGUI (new session) button disable in Netweaver

    Hi all, I have a few users where their SAPGUI's "New Session" button is disable if they launch it via Netweaver (single-sign on). However, if they sign in to another computer, this issue did not arise. Likewise, any user that sign in to this particul

  • Regex to split a String

    Hi, Here's a little regex problem Jos e-mailed me the other day, to which I didn't find a satisfactory answer (I found one, but it's rather verbose). Chances are that there is no short (or simple) solution, but when this is the case with a certain pr