Help with Threads

I need help with threads. How can I break this code into teo threads without chaning the data objects at all? Producer will produce string line by line and consumer will take the line and search for the word. Help me please.
Thank you
public class WordFinder
* Main program opens the file given by the user as an argument and
* searches for the word given by the user. If the word is found,
* the line number on which the word occurs is displayed.
* @param args[0] Word to search for
* @param args[1] Name of file to search
public static void main(String[] args) throws IOException
// To keep track of how long the program runs we'll set the startTime
// variable to the current time in milliseconds and use that at
// the end of the program to find out how long we ran.
long startTime = System.currentTimeMillis();
String wordToFind;
String currentLine;
int lineCount = 0; // Keep track of line numbers
BufferedReader inputFile = null; // Needed to get compiler to quit
// complaining about uninitialized
// variables.
// Make sure we have 2 arguments passed to us
if (args.length < 2)
// Nope. Show user how to run and then exit with an error (1)
System.out.println("usage: java WordFinder <word> <file pathname>");
System.exit(1);
// So far, so good. Now try to open the file the user gave us as
// a parameter. We'll use a BufferedReader object to read the file
// so we can read one line at a time from the input. If opening the
// file fails, print an error message and exit with an error (1).
try
inputFile = new BufferedReader(new FileReader(args[1]));
catch (FileNotFoundException e)
System.out.println(args[1] + ": File not found or is not readable");
System.exit(1);
// Set the wordToFind variable to refer to args[0]. We don't
// really need to do this, but it makes our code more readable
wordToFind = args[0];
// We're going to read the file one line at a time. For each
// line, we'll create a StringTokenizer object to break the line
// into distinct words, checking each word to see if it's the same
// as the given search word.
// Read first line from the file
currentLine = inputFile.readLine();
while (currentLine != null) // Repeat until we reach EOF
// Have a valid input line, increment the counter
lineCount++;
// Create a StringTokenizer object over the current line
StringTokenizer tokens = new StringTokenizer(currentLine);
// Check each word in the string by accessing each token
while (tokens.hasMoreTokens())
// See if the next word is the one we're looking for and
// advance the token iterator to the next token
if (wordToFind.equals(tokens.nextToken()))
// Yes, display the current line number
System.out.println(wordToFind + " found on line " + lineCount);
// Read next line from the file
currentLine = inputFile.readLine();
} // while
// Done with the input file
inputFile.close();
// Display the running time of this program in milliseconds by
// subtracting the start time from the current time
System.out.println((System.currentTimeMillis() - startTime) + " milliseconds");
} // main
} // WordFinder

You may create Queue object. (I guess that you're already know QUEUE)
Then ... use producer thread to load input file into queue. (Enqueue)
Consumer ... dequeue
Queue can be empty because of
- Input file was read to EOF and Consumer had produced all queue.
or
- Cunsumer works too fast... So the queue is empty.
So, you may have to use ... wait() in Consumer in case of the queue is empty.
And use notify() in Producer to wake up consumer ...
Is this right ?

Similar Messages

  • Help with Thread dump analisys

    We have problems with our application which runs on bea8.1 sp1.
    Problem is that bea runs out from Threads (StuckThreads).
    thread dums look same for all threads but i can's see what is wrong.
    Here are dumps from first and last threads :
    "ExecuteThread: '1' for queue: 'weblogic.kernel.Default'" daemon prio=5 tid=0x7f3628
    nid=0xd runnable [a6280000..a6281994
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:129)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:183)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:201)
    - locked <c3197aa0> (a java.io.BufferedInputStream)
    at java.io.DataInputStream.readByte(DataInputStream.java:276)
    at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:189)
    at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:133)
    at com.hutchison3g.core.product.homebase.services.HomebaseFactoryImpl_Stub.getIdentity(Unknown
    Source)
    at com.hutchison3g.core.product.homebase.client.HomebaseClient.getIdentity(HomebaseClient.java:207)
    at com.hutchison3g.core.product.homebase.client.util.HomebaseProxy.getIdentity(HomebaseProxy.java:78)
    at com.hutchison3g.core.product.homebase.client.util.UserUtil.getIdentity(UserUtil.java:132)
    at com.hutchison3g.core.product.homebase.servlets.TalonUniServlet.doGet(TalonUniServlet.java:181)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at com.hutchison3g.core.product.homebase.client.servlet.core.HomebaseCommonServlet.service(HomebaseCommonServlet.
    java:72)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1053)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:387)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:305)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:6310)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:317)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:118)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3622)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2569)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
    "ExecuteThread: '24' for queue: 'weblogic.kernel.Default'" daemon prio=5 tid=0x6dd548
    nid=0x24 runnable [a3d80000..a3d819
    94]
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:129)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:183)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:201)
    - locked <c30c5010> (a java.io.BufferedInputStream)
    at java.io.DataInputStream.readByte(DataInputStream.java:276)
    at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:189)
    at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:133)
    at com.hutchison3g.core.product.homebase.services.HomebaseFactoryImpl_Stub.getIdentity(Unknown
    Source)
    at com.hutchison3g.core.product.homebase.client.HomebaseClient.getIdentity(HomebaseClient.java:207)
    at com.hutchison3g.core.product.homebase.client.util.HomebaseProxy.getIdentity(HomebaseProxy.java:78)
    at com.hutchison3g.core.product.homebase.client.util.UserUtil.getIdentity(UserUtil.java:132)
    at com.hutchison3g.core.product.homebase.servlets.TalonUniServlet.doGet(TalonUniServlet.java:181)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at com.hutchison3g.core.product.homebase.client.servlet.core.HomebaseCommonServlet.service(HomebaseCommonServlet.
    java:72)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1053)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:387)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:305)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:6310)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:317)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:118)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3622)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2569)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)

    Rob Woollen <[email protected]> wrote:
    Can you post the full thread dump?
    It looks like you have some code making an RMI call over the network.
    Is it calling another server, or perhaps a loopback call into the same
    server. The latter (opening a socket to your own process) is a good
    way
    to get a deadlock.
    -- Rob
    dara wrote:
    We have problems with our application which runs on bea8.1 sp1.
    Problem is that bea runs out from Threads (StuckThreads).
    thread dums look same for all threads but i can's see what is wrong.
    Here are dumps from first and last threads :
    "ExecuteThread: '1' for queue: 'weblogic.kernel.Default'" daemon prio=5tid=0x7f3628
    nid=0xd runnable [a6280000..a6281994
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:129)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:183)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:201)
    - locked <c3197aa0> (a java.io.BufferedInputStream)
    at java.io.DataInputStream.readByte(DataInputStream.java:276)
    at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:189)
    at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:133)
    at com.hutchison3g.core.product.homebase.services.HomebaseFactoryImpl_Stub.getIdentity(Unknown
    Source)
    at com.hutchison3g.core.product.homebase.client.HomebaseClient.getIdentity(HomebaseClient.java:207)
    at com.hutchison3g.core.product.homebase.client.util.HomebaseProxy.getIdentity(HomebaseProxy.java:78)
    at com.hutchison3g.core.product.homebase.client.util.UserUtil.getIdentity(UserUtil.java:132)
    at com.hutchison3g.core.product.homebase.servlets.TalonUniServlet.doGet(TalonUniServlet.java:181)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at com.hutchison3g.core.product.homebase.client.servlet.core.HomebaseCommonServlet.service(HomebaseCommonServlet.
    java:72)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1053)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:387)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:305)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:6310)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:317)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:118)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3622)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2569)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
    "ExecuteThread: '24' for queue: 'weblogic.kernel.Default'" daemon prio=5tid=0x6dd548
    nid=0x24 runnable [a3d80000..a3d819
    94]
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:129)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:183)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:201)
    - locked <c30c5010> (a java.io.BufferedInputStream)
    at java.io.DataInputStream.readByte(DataInputStream.java:276)
    at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:189)
    at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:133)
    at com.hutchison3g.core.product.homebase.services.HomebaseFactoryImpl_Stub.getIdentity(Unknown
    Source)
    at com.hutchison3g.core.product.homebase.client.HomebaseClient.getIdentity(HomebaseClient.java:207)
    at com.hutchison3g.core.product.homebase.client.util.HomebaseProxy.getIdentity(HomebaseProxy.java:78)
    at com.hutchison3g.core.product.homebase.client.util.UserUtil.getIdentity(UserUtil.java:132)
    at com.hutchison3g.core.product.homebase.servlets.TalonUniServlet.doGet(TalonUniServlet.java:181)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at com.hutchison3g.core.product.homebase.client.servlet.core.HomebaseCommonServlet.service(HomebaseCommonServlet.
    java:72)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1053)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:387)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:305)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:6310)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:317)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:118)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3622)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2569)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
    Thanks Rob,
    sorry for delay but I was on vacation.
    You are right about RMI, our app. consist from FE (front end) and BE (back end),
    comunication between them is RMI.
    We had some problems with BE but now we have new version and it looks ok.
    Anyway thanks for help, if I will have again some problems then it will be
    Help with thread analisys 2 ;-)

  • Need help with threads?.. please check my approach!!

    Hello frnds,
    I am trying to write a program.. who monitors my external tool.. please check my way of doing it.. as whenever i write programs having thread.. i end up goosy.. :(
    first let me tell.. what I want from program.. I have to start an external tool.. on separate thread.. (as it takes some time).. then it takes some arguments(3 arguments).. from file.. so i read the file.. and have to run tool.. continously.. until there are arguments left.. in file.. or.. user has stopped it by pressing STOP button..
    I have to put a marker in file too.. so that.. if program started again.. file is read from marker postion.. !!
    Hope I make clear.. what am trying to do!!
    My approach is like..
    1. Have two buttons.. START and STOP on Frame..
    START--> pressed
    2. check marker("$" sign.. placed in beginning of file during start).. on file..
         read File from marker.. got 3 arg.. pass it to tool.. and run it.. (on separate thread).. put marker.. (for next reading)
         Step 2.. continously..
    3. STOP--> pressed
         until last thread.. stops.. keep running the tool.. and when last thread stops.. stop reading any more arguments..
    Question is:
    1. Should i read file again and again.. ?.. or read it once after "$" sign.. store data in array.. and once stopped pressed.. read file again.. and put marker ("$" sign) at last read line..
    2. how should i know when my thread has stopped.. so I start tool again??.. am totally confused.. !!
    please modify my approach.. if u find anything odd..
    Thanks a lot in advance
    gervini

    Hello,
    I have no experience with threads or with having more than run "program" in a single java file. All my java files have the same structure. This master.java looks something like this:
    ---master.java---------------------------------------------------
    import java.sql.*;
    import...
    public class Master {
    public static void main(String args []) throws SQLException, IOException {
    //create connection pool here
    while (true) { // start loop here (each loop takes about five minutes)
    // set values of variables
    // select a slave process to run (from a list of slave programs)
    execute selected slave program
    // check for loop exit value
    } // end while loop
    System.out.println("Program Complete");
    } catch (Exception e) {
    System.out.println("Error: " + e);
    } finally {
    if (rSet1 != null)
    try { rSet1.close(); } catch( SQLException ignore ) { /* ignored */ }
    connection.close();
    -------end master.java--------------------------------------------------------
    This master.java program will run continuously for days or weeks, each time through the loop starting another slave process which runs for five minutes to up to an hour, which means there may be ten to twenty of these slave processes running simultaneously.
    I believe threads is the best way to do this, but I don't know where to locate these slave programs: either inside the master.java program or separate slave.java files? I will need help with either method.
    Your help is greatly appreciated. Thank you.
    Logan

  • Need some help with threads...

    Hello all,
    I am working on a project at work, and I am not the best programmer in the world. I have been trying to get my head around this for a couple of days and just cannot get it to work.
    I am writing an instrumentation control program that will have three threads. One is the GUI, one will receive control information and set up the hardware, and one will check the hardware status and report it to the GUI periodically. I plan on using the invokeLater() method to communicate the status to the GUI and change the status display in the GUI. Communication from the GUI to the controller thread and from the status thread to the controller thread I had planned on being piped input/output stream as appropriate. I have a control class and a status class that need to be communicated over these piped streams. In some trial code I have been unable to wrap the piped input/output streams with object input/output streams. I really need some help with this. Here is the main thread code:
    package playingwiththreads1;
    import java.io.*;*
    *public class PlayingWithThreads1 {*
    public static void main(String[] args) {*
    * PipedOutputStream outputPipe = new PipedOutputStream();*
    * ObjectOutputStream oos = null;*
    * ReceiverThread rt = new ReceiverThread(outputPipe);*
    // Start the thread -- First try*
    * Thread t = new Thread(rt);*
    t.start();*
    // Wrap the output pipe with an ObjectOutputStream*
    try*
    oos = new ObjectOutputStream(outputPipe);*
    catch (IOException e)*
    System.out.println(e);*
    // Start the thread -- Second try*
    //Thread t = new Thread(rt);*
    //t.start();*
    /** Send an object over the pipe. In reality this object will be a
    class that contains control or status information */
    try
    if (!oos.equals(null))
    oos.writeObject(new String ("Test"));
    catch (IOException e)
    try
    Thread.sleep(5000);
    catch (InterruptedException e)
    I read somewhere that it matters where you start the thread relative to where you wrap piped streams with the object streams. So, I tried the two places I felt were obvious to start the thread. These are noted in the comments. Here is the code for the thread.
    package playingwiththreads1;
    import java.io.*;
    public class ReceiverThread implements Runnable {
    private PipedInputStream inputPipe = new PipedInputStream();
    private ObjectInputStream inputObject;
    ReceiverThread (PipedOutputStream outputPipe)
    System.out.println("Thread initialization - start");
    try
    inputPipe.connect(outputPipe);
    inputObject = new ObjectInputStream(inputPipe);
    catch (IOException e)
    System.out.println(e);
    System.out.println("Thread initialization - complete");
    public void run()
    System.out.println("Thread started");
    try
    if (inputObject.available() > 0)
    System.out.println(inputObject.read());
    catch (IOException e)
    System.out.println(e);
    Through testing I have determined that no matter where I start the thread, the thread never gets past the "inputObject = new ObjectInputStream(inputPipe);" assignment.
    Could someone please help me with this? There are other ways for me to write this program, but this is the one that I would like to make work.
    Many thanks in advance,
    Rob Hix
    Edited by: RobertHix on Oct 6, 2009 3:54 AM

    Thanks for the help, but that did not work. I tried flushing the ObjectOutputStream and it is still hanging when initializing the thread.
    Here is a better look at the code since I was helped to figure out how to insert it:
    The main method:
    package playingwiththreads1;
    import java.io.*;
    public class PlayingWithThreads1 {
        public static void main(String[] args) {
            PipedOutputStream outputPipe = new PipedOutputStream();
            ObjectOutputStream oos = null;
            ReceiverThread rt = new ReceiverThread(outputPipe);
            // Start the thread -- First try
            //Thread t = new Thread(rt);
            //t.start();
            // Wrap the output pipe with an ObjectOutputStream
            try
                oos = new ObjectOutputStream(outputPipe);
                oos.flush();
            catch (IOException e)
                System.out.println(e);
            // Start the thread -- Second try
            Thread t = new Thread(rt);
            t.start();
            /* Send an object over the pipe.  In reality this object will be a
             * class that contains control or status information */
            try
                if (!oos.equals(null))
                    oos.writeObject(new String ("Test"));
                    oos.flush();
            catch (IOException e)
                System.out.pringln(e);
            try
                Thread.sleep(5000);
            catch (InterruptedException e)
    }The thread code:
    package playingwiththreads1;
    import java.io.*;
    public class ReceiverThread implements Runnable {
        private PipedInputStream inputPipe = new PipedInputStream();
        private ObjectInputStream inputObject;
        ReceiverThread (PipedOutputStream outputPipe)
            System.out.println("Thread initialization - start");
            try
                inputPipe.connect(outputPipe);
                inputObject = new ObjectInputStream(inputPipe);
            catch (IOException e)
                System.out.println(e);
            System.out.println("Thread initialization - complete");
        public void run()
            System.out.println("Thread started");
            try
                if (inputObject.available() > 0)
                    System.out.println(inputObject.read());
            catch (IOException e)
                System.out.println(e);
    }Does anyone else have and ideas?

  • Wanted: Help with thread in spanish; guitar not recording

    Can someone please help with this thread?
    GarangeBand No Reconoce Mi Guitarra Audio
    The op has trouble to connect his guitar. I cannot interview him in spanish, and he does not know to ask in English.
    Appriciate any help.
    Léonie

    Hi Borris12,
    I'll clear this up for you and let you know whats happened.
    Could you drop me in an email please with your BT account and telephone number along with a link back to this thread.
    Just send to the email address in my profile and mark FAO Craig please.
    Thx
    Craig
    BTCare Community Mod
    If we have asked you to email us with your details, please make sure you are logged in to the forum, otherwise you will not be able to see our ‘Contact Us’ link within our profiles.
    We are sorry but we are unable to deal with service/account queries via the private message(PM) function so please don't PM your account info, we need to deal with this via our email account :-)”
    td-p/30">Ratings star on the left-hand side of the post.
    If someone answers your question correctly please let other members know by clicking on ’Mark as Accepted Solution’.

  • Need some help with threads, urgent!!

    Hi I am really new to threads and I cannot figure out why the code below will not work. After my thread goes into a wait, it never wakes up. Can someone please help me? When stepping through the code, I get an invalid stack frame message as well. Thanks in Advance!!!
    Colin
    import java.io.*;
    import java.util.*;
    public class XMLInputCompression extends InputStream implements Runnable
    private InputStream in;
    private ByteArrayOutputStream baos = new ByteArrayOutputStream();
    private boolean closed = false;
    private boolean foundDTD = false;
    private Vector elementsList = new Vector();
    private Vector attributesList = new Vector();
    private BufferedReader br = null;
    private StringTokenizer st = null;
    final static int BUFF_SIZE = 500;
    final static String HEADER = "<?xml version=\"1.0\"?><!DOCTYPE Form SYSTEM ";
    final static char CLOSE_ELEMENT = '>';
    final static String END_ELEMENT = ">";
    final static char START_ELEMENT = '<';
    final static char START_ATTRIBUTE = '[';
    final static String ATTLIST = "<!ATTLIST";
    final String XMLTAG ="<?xml";
    final String ELEMENTTAG = "<!ELEMENT";
    public static void main(String[] args)
         try
    FileInputStream fis = new FileInputStream("c:/Dump.txt");
    XMLInputCompression compress = new XMLInputCompression(fis);
    int r = 0;
    while(r != -1)
    byte b[] = new byte[200];
    r = compress.read(b);
    System.out.println("r is: " + r);
    if( r == -1)
    compress.close();
    }catch(Exception e)
    e.printStackTrace();
    } // end main
    public XMLInputCompression(InputStream is) throws IOException
    this.in = is;
    baos.write(HEADER.getBytes());
    new Thread(this).start();
    public void run()
    try
    Vector elementNames = new Vector();
    //Vector attributeNames = new Vector();
    StringBuffer sb = new StringBuffer(BUFF_SIZE);
    char c = (char)in.read();
    switch (c)
    case START_ELEMENT:
    if (!foundDTD)
    wakeUp(sb.toString().getBytes());
    //populate the elements and atrributes vectors
    FileInputStream fis = new FileInputStream("C:/form.dtd");
    processDTDElements(fis);
    foundDTD = true;
    sb.setLength(0);
    else
    sb.append("<");
    String element = (String)elementsList.get((int)in.read());
    elementNames.addElement(element);
    sb.append(element);
    wakeUp(sb.toString().getBytes());
    //baos.write(sb.toString().getBytes());
    sb.setLength(0);
    break;
    case START_ATTRIBUTE:
    sb.append("[");
    sb.append(attributesList.get((int)in.read()));
    wakeUp(sb.toString().getBytes());
    //baos.write(sb.toString().getBytes());
    sb.setLength(0);
    break;
    case CLOSE_ELEMENT:
    wakeUp(sb.toString().getBytes());
    //baos.write(sb.toString().getBytes());
    sb.setLength(0);
    sb.append(elementNames.get(0));
    elementNames.remove(0);
    sb.append(">");
    break;
    default:
    sb.append(c);
    synchronized (baos)
    baos.notify();
    System.out.println(" in run method*****");
    }catch(Exception e)
    e.printStackTrace();
    } // end run
    private void wakeUp(byte b[])
    System.out.println(" in wakeup method*****");
    synchronized (baos)
    try
    baos.write(b);
    catch(Exception e)
    System.out.println("exception caught");
    e.printStackTrace();
    baos.notify();
    public boolean markSupported()
    return false;
    public int read(byte[] b1, int off, int len) throws IOException
    return readData(b1, off, len);
    public int read() throws IOException
    return readData(null, 0, 1);
    public int read(byte[] b1) throws IOException
    return readData(b1, 0, b1.length);
    private int readData(byte[] b1, int off, int len) throws IOException
    String s = null;
    while(true)
    if (closed && baos.size() == 0)
    return -1;
    int size = baos.size();
    if (baos.size() > 0) // Have at least one byte
    if( b1 == null)
    byte b[] = baos.toByteArray();
    baos.reset();
    baos.write(b, 1, b.length-1); // baos contains all data except b[0]
    return b[0];
    else
    int minLen = Math.min(baos.size(), len);
    //System.out.println(" baos contents are: " + baos.toString());
    byte b[] = baos.toByteArray();
    s = b.toString();
    int length = baos.size() - minLen;
    baos.reset();
    baos.write(b, 0, length );
    System.arraycopy(b, 0, b1, off, minLen);
    return minLen;
    try
    synchronized (baos)
    if (!closed)
    baos.wait();
    catch(java.lang.InterruptedException ie)
    ie.printStackTrace();
    }// end read data
    private boolean hasMoreTokens()
    String s = null;
    try
    if (br != null)
    if (st == null || !st.hasMoreTokens())
    // read in a line, create a st
    s = br.readLine();
    st = new StringTokenizer(s,"\n\r\t ");
    }catch(Exception e)
    e.printStackTrace();
    return st.hasMoreTokens();
    private String nextToken() throws Exception
    String token = null;
    if(st.hasMoreTokens())
    token = st.nextToken();
    }else
    String s = br.readLine();
    st = new StringTokenizer(s,"\n\r\t ");
    token = st.nextToken();
    return token;
    private void processDTDElements(FileInputStream is)
    try
         // get the file desriptor from the input Stream
         FileDescriptor fd = is.getFD();
         // create a new buffered reader
    br = new BufferedReader(new FileReader(fd));
    boolean lookForEndTag=false;
    boolean lookForEndAtt=false;
    while (hasMoreTokens())
    String token = nextToken();
    if (lookForEndTag)
    if (!token.endsWith(END_ELEMENT))
    continue;
    }else
    lookForEndTag = false;
    continue;
    if (token.startsWith(XMLTAG))
    lookForEndTag = true;
    else if (token.startsWith(ELEMENTTAG))
    token = nextToken();
    if ( elementsList.indexOf(token)<0)
    elementsList.addElement(token);
    lookForEndTag = true;
    else if (token.startsWith(ATTLIST))
    String dummy = nextToken(); // discard element name
    do
    token = nextToken();
    if (token.endsWith(">"))
    break;
    if (attributesList.indexOf(token)<0 )
    attributesList.addElement(token);
    token = nextToken();
    if ( token.startsWith("CDATA") || token.startsWith("ID") )
    token = nextToken();
    if (token.equals("#FIXED "))
    token = nextToken();
    lookForEndAtt = token.endsWith(END_ELEMENT);
    else if ( token.startsWith("(") )
    do
    token = nextToken();
    }while ( token.indexOf (")") == -1);
    token = nextToken();
    lookForEndAtt = token.endsWith(END_ELEMENT);
    } while (!lookForEndAtt);
    }//end if
    }//end while
    }catch(Exception e)
    e.printStackTrace();
    }finally
    try
    br.close();
    }catch(Exception e)
    e.printStackTrace();
    }// end process elements
    public void close() throws IOException
    closed = true;
    synchronized(baos)
    baos.notify();
    }// end XMLinputCompression class

    Your problem probably has something to do with where you tell baos (or rather, the thread that it is in) to wait. You have:synchronized (baos)
        if (!closed)
            baos.wait();
    }Which acquires a lock on baos, then tells its own thread to wait without ever relinquishing its lock on baos. So when your main method calls the read method, it hangs immediately when it tries to access baos because it is still locked. So what you're seeing is a basic deadlock condition.
    Really, you're not gaining anything with your multithreading in this case. But that's a different issue.

  • Need help with Threading GUI progress bar

    Anyone able to help? I'm sure you've seen this a million times. I've google'd around and tried examples but still can't get a progress bar to work properly under the following situation:
    1. Created a panel with several components to select directory, display directory in tree etc.
    2. When a specific button (Search) is clicked, I want a secondary window to popup and report progress of searching down the directory.
    As you'll probably guess, the progress window isn't being updated until the end. I'm using Threads and using InvokeLater but nothing happens. Is there any good example that does the above? I can't seem to find one to figure this out.
    Thanks
    Speedy.
    Sample code:
    main.java:
    ========
    public class Main {
    public static void main(String[] args) {
    MainPanel mainPanel = new MainPanel();
    mainPanel.show();
    MainPanel.java:
    ============
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    public class MainPanel extends JFrame implements ActionListener {
    public MainPanel() {
    this.setSize(100,100);
    JButton startButton = new JButton("Start");
    this.getContentPane().add(startButton);
    startButton.addActionListener(this);
    public void actionPerformed(ActionEvent event) {
    ProgressPanel pp = new ProgressPanel();
    pp.show();
    SimpleTask st = new SimpleTask(pp);
    st.start();
    while (st.isAlive()) {
    System.err.println("waiting..");
    try {
    Thread.sleep(100);
    } catch (Exception e) {};
    System.err.println("finished!");
    SimpleTask.java:
    =============
    import javax.swing.SwingUtilities;
    public class SimpleTask extends Thread {
    ProgressPanel pp = null;
    public SimpleTask(ProgressPanel _pp) {
    pp = _pp;
    this.setDaemon(true);
    int i = 0;
    String position = "";
    public void run() {
    Runnable updateGUI = new Runnable() {
    public void run() {
    pp.setText(position);
    try {
    for (i=0; i<50; i++) {
    position = "Now on = " + new Integer(i).toString();
    System.err.println(position);
    SwingUtilities.invokeLater(updateGUI);
    sleep(100);
    } catch (Exception e) {}
    ProgressPanel.java:
    ===============
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class ProgressPanel extends JFrame {
    private JLabel label = new JLabel();
    public ProgressPanel() {
    this.setSize(200,200);
    this.setLocation(100,100);
    this.getContentPane().add(label);
    setText("Start");
    public void setText(String text) {
    label.setText(text);
    }

    Ok, I'll look down that road. I should have said the Thread is being used because the current while loop will be changed to perform real work. Just an example at the moment to show what I'm trying to do. Does this make a difference? The real task will be to drill down directories, counting file types/dirs etc...

  • Help with Threads in java...

    Hi all,
    the problem it's the following:
    i got a program that update a sql server table. So i want, at the same time, run this program many times, say 10 for example, to do it that faster.
    But i only want 10 subprograms at the same time. So i got to use wait() and others method's, rigth?
    I'm not shure about this, because a never use threads.
    So any help, code or "pseudocode" will be very appreciated.
    Thanks in advance
    A. Santos

    Hi santhos,
    If u use 10 threads to read the sql table, then
    ur program will lose the sequence. If u have a idea
    to split the program then u can use threads.
    Regards,
    Palaniyappan

  • Please ..... Help with Threads

    I got the same problem that sun_fade has which is related to running a program behind the scene ..... this the topic that sun_fade issued
    ((((((Am currently working on a small java project which run through a unix terminal ... my program take some time (about 20 seconds ) to do some checking and calculations... My question is that when I run this program I need to wait for this 20 seconds or what ever my program take and after that I will get the result ... what I want is to make the control go back to system so i can issue some commands and do some stuff and when the program is done I will get the result .... exactly when you issue >>>> httpd start and you press enter ....
    Thanks in advance )))))
    and some guys answers that we can do such a thing by using a Threads ..... so what I want is just a simple program that type a message like "" hello Dude """ after 2 minutes ,showing this message on the terminal and also during this time the control is back to the system so I can issue some commands and after time elapsed the message will appear .....
    for example---
    bash:- java hellodude
    bash:- // and I can do what I want issuing commands what ever ..... etc
    when 2 minutes elapsed
    Hello dude
    bash:-
    Thanks

    sunfade wrote:
    I got the same problem that sun_fade hasBecause you are him.
    ((((((Am currently working on a small java project which run through a unix terminal ... my program take some time (about 20 seconds ) to do some checking and calculations... My question is that when I run this program I need to wait for this 20 seconds or what ever my program take and after that I will get the result ... what I want is to make the control go back to system so i can issue some commands and do some stuff and when the program is done I will get the result .... exactly when you issue >>>> httpd start and you press enter ....
    Thanks in advance )))))
    and some guys answers that we can do such a thing by using a Threads ..... so what I want is just a simple program that type a message like "" hello Dude """ after 2 minutes ,showing this message on the terminal and also during this time the control is back to the system so I can issue some commands and after time elapsed the message will appear ..... You're still not explaining your problem well at all.
    >
    for example---
    bash:- java hellodude
    bash:- // and I can do what I want issuing commands what ever ..... etc
    when 2 minutes elapsed
    Hello dude
    bash:- There are two ways two do that. You've already been told one. I'm not going to tell you the other one because I don't like your attitude.
    I will tell you this, though: That's probably a stupid thing to do. I don't want some output from a previous command popping out in the middle of other work I'm doing. If I really do, I'll explicitly say so with &.
    Actually, now that I think about it, the second way might not work anyway.
    There's a third way though, but it will be heinously ugly. The only sensible way to do that is to use &. A more sensible way would be, as sabre suggested, to use a separate terminal

  • Need help with threading in Swing GUI !!!

    I've written an app that parses and writes
    files. I'm using a Swing GUI. The app
    could potenially be used to parse hundreds or even
    thousands of files. I've included a JProgressBar
    to monitor progress. The problem is when I parse
    a large number of files the GUI freezes and only
    updates the values of the progress bar when the
    parsing and writing process is finished.
    I assume I need to start the process in a seperate thread. But, I'm new to threads and I'm not sure
    whether to start the Progressbar code in a seperate
    thread or the parsing code. As a matter of fact I really
    don't have any idea how to go about this.
    I read that Swing requires repaints be done in the
    event dispatch thread. If I start the parsing in a seperate
    thread how do I update the progressbar from the other
    thread? I'm a thread neophyte.
    I need a cigarette.

    In other words do this:
    Inside event Thread:
    handle button action
    start thread
    return from action listener
    Inside worker Thread:
    lock interface
    loop
    perform action
    update progress bar
    unlock interface
    return from worker ThreadDoesn't updating the progress bar (and locking/unlocking the interface components) from within the worker thread violate the rule that you shouldn't mess with Swing components outside the event thread? (Do I have that rule right?)
    In any case, is there any way to just post some kind of event to the progress bar to update it from within the worker thread, thereby insuring that the GUI progress bar update is being invoked from the event thread? This would also obviate the need to use a timer to poll for an update, which I think is a waste especially when the monitored progress is at a variable rate, (or for number crunching, is executing on different speed machines).
    Also, doesn't using invokeLater() or invokeAndWait() still block the event dispatching thread? I don't understand how having a chunk of code started in the event thread doesn't block the event thread unless the code's executed in a "sub-thread", which would then make it not in the event thread.
    I'm also looking to have a progress bar updated to monitor a worker thread, but also want to include a "Stop" button, etc. and need the event queue not to be blocked.
    The last thing I can think of is to implement some kind of original event-listener class that listens to events that I define, then register it with the system event queue somehow, then have the worker thread post events to this listener which then calls setValue() in the progress bar to insure that the bar is updated from the event queue and when I want it to be updated. I don't know yet if it's possible to create and register these kinds of classes (I'm guessing it is).
    Thanks,
    Derek

  • Help with Threads for a webserver

    That is the main class of my webserver. The problem is that after executing one petition the server closes with exit status 1. Normally that should never happens as it does not happen at the single-threaded server. Any suggestions ??
    Also do i have to impement monitors, meaning syncronized functions to monitor buffers and some static variables ?
    This is my first program impementing threads so really i do not experience over it
    package jhttp_server;
    import java.io.*;
    import java.net.*;
    import java.lang.*;
    * <p>Title: JHTTP_server</p>
    * <p>Description: A simple HTTP server implemented with Java</p>
    * <p>Copyright: Copyright (c) 2004 - Lisenced under GPL</p>
    * <p>Company: Universidad Rey Juan Carlos</p>
    * @author Panayiotis Papadopoulos -> [email protected]
    * @version 0.1
    public class jserver {
    static ServerSocket serverSocket = null;
    static PrintWriter out;
    static BufferedReader in;
    static Socket client = null;
    static short i=0;
    static int port;
    static boolean newSock=true;
    public static void main(String[] args) throws IOException {
    port = Integer.valueOf(args[0]).intValue();
    try {
         serverSocket = new ServerSocket(port);
    catch (IOException e) {
         System.out.println("Must Enter a port number");
    System.out.println("|------------------------------------------------------------------------|");
    System.out.println("|JHTTP Server initialized and accepting connections on port:" +
    serverSocket.getLocalPort()+"\t |");
    System.out.println("|------------------------------------------------------------------------|");
    while(true){
    while (i < 5) {
    i++;
    try {
    //Creating if needed a new socket where the clients listens
    if (newSock) {
    client = serverSocket.accept();
    in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    out = new PrintWriter(client.getOutputStream());
    System.out.println("LOG: Client is listening on port: "+client.getPort());
    //Here the server creates a new thread for the petition
    petition newPet = new petition();
    newPet.T.start();
    } // try- create input and output buffers
    catch (UnknownHostException e) {
    System.err.println("JHTTP Server could establish a connection. Exiting...");
    catch (IOException e) {
    System.err.println("Could not get I/O for the connection to client.");
    } //try - create client sockets, wait and attend connection
    } //while 5 petitions
    System.out.println("Session Closed. 5 continious petitions served.");
    out.close();
    in.close();
    client.close();
    newSock = true;
    System.gc();
    i=0;
    } // while - forever
    }// -------------------main-------------------
    }// jserver - main class of JHTTP server project
    class petition implements Runnable {
    Thread T;
    petition () {
    T = new Thread(this);
    T.start();
    public void run() {
    try {
    //Analyse petition
    Petition_Analysis.Analyse_Petition(jserver.in);
    //Then Attend it
    if (Petition_Analysis.pt.Version.equals("v10"))
    Http_10.Attend_Petition(Petition_Analysis.pt, jserver.out, extra.detectConnectionAlive());
    else if (Petition_Analysis.pt.Version.equals("v11"))
    Http_11.Attend_Petition(Petition_Analysis.pt, jserver.out, extra.detectClose());
    else {
    jserver.out.print("HTTP/1.0 400 Bad Request\r\n\r\n");
    jserver.out.close();
    jserver.in.close();
    jserver.client.close();
    jserver.newSock = true;
    //The following function immediately prints the contents of the PrinterBuffer
    jserver.out.flush();
    System.gc();
    catch (MalformedURLException murle) {
    jserver.out.print("HTTP/1.0 400 Bad Request\r\n\r\n");
    try { jserver.client.close(); }
    catch(IOException ioe) { System.out.println(ioe); }
    jserver.newSock = true;
    catch (NullPointerException npe) {}
    //try - analyse petition & attend it
    catch (IOException ioe){
    System.out.println(ioe);
    } // -- run()
    } // --class: thread

    Use code tags when posting code.
    Given that the code you presented does not call System.exit() I am not sure how it could be exiting with a value of 1.
    When you accept a connection from a client the code should do nothing but pass the client socket off to a thread and then start that thread. It should not extract the streams - do that in the thread.
    The in/out streams of the client socket should be wholly contained within the thread/Runnable. They do not belong to the class that holds the SockerServer.
    Your catch blocks need to be reworked. The first one completely ignores the exception and prints out that a port number is needed. You should be printing the exception message at a minimum and right now you should be be doing a printStackTrace() as well. Additionally you are ignoring a null pointer exception and that is wrong.

  • Creating breakout game. Need help with thread starting.

    Howdy. As the title says, I've got an assignment to make a breakout game. So far it's going alright, but I've run into a rather large snag...I can't get it to animate :P I've got my main applet, then I created a class heirarchy for the paddle, ball, and brick objects. For this question, lets just focus on the ball object.
    This is my applet code so far (it is not even close to being done, so don't laugh :P )
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    * Class BreakoutApplet - Plays a simple game of Breakout.
    * @author Kris Nelson
    * @version November 10, 2004
    public class BreakoutApplet extends JApplet implements Runnable
        protected Brick brick; // creates an object of class brick
        protected Ball ball; // creates an object of class ball
        protected Paddle paddle; // creates an object of class paddle
        protected boolean running; // tells the program whether or not the thread is running
        protected ArrayList brickArray = new ArrayList(); // stores all the bricks in the game
        protected Thread timer; // the thread which controls the animation for the applet
        * Called by the browser or applet viewer to inform this JApplet that it
        * has been loaded into the system. It is always called before the first
        * time that the start method is called.
        public void init()
            // this is a workaround for a security conflict with some browsers
            // including some versions of Netscape & Internet Explorer which do
            // not allow access to the AWT system event queue which JApplets do
            // on startup to check access. May not be necessary with your browser.
            JRootPane rootPane = this.getRootPane();   
            rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
            createBricks(); // creates the games array of bricks
            ball = new Ball(400, 400, 2, 2); // sets the values for the ball
            paddle = new Paddle(300, 660, 2); // sets the values for the paddle
            // !!!!!!! have tried placing ball.start() here
        * Paint method for applet.
        * @param  g   the Graphics object for this applet
        public void paint(Graphics g)
            // draws the background, border, and all the games objects
            g.setColor(Color.lightGray); // sets the drawing color to light gray
            g.fillRect(0, 0, 600, 700); // displays the game screens background
            displayBorder(g); // displays the game screens border
            displayBricks(g); // displays the array of bricks
            ball.display(g); // displays the ball
            paddle.display(g); // displays the paddle
        * Creates the games array of bricks
        public void createBricks()
            int colorNumber = 1; // starts the color of the bricks at orange
            double yPosition = 100; // starts the bricks y screen position at 100
            for(int i = 0; i < 4; i++)
                double xPosition = 12; // starts the bricks x screen position at 12
                for(int j = 0; j < 8; j++)
                    if(colorNumber == 0)
                        colorNumber = 1; // sets the color of the bricks to orange
                    else
                        colorNumber = 0; // sets the color of the bricks to green
                    brickArray.add(brick = new Brick(xPosition, yPosition, colorNumber)); // adds a brick to the current container in the brick array
                    xPosition = xPosition + brick.getWidth(); // move the bricks x screen position to the next column
                yPosition = yPosition + brick.getHeight(); // moves the bricks y screen position to the next row
                if(colorNumber == 0)
                    colorNumber = 1; // sets the color of the bricks to orange
                else
                    colorNumber = 0; // sets the color of the bricks to green
        * Displays the game screens border
        * @param  g   the Graphics object for this applet
        public void displayBorder(Graphics g)
            g.setColor(Color.black); // sets the drawing color to black
            g.fillRect(0, 0, 600, 24); // draws a border on the top of the screen
            g.fillRect(0, 0, 12, 700); // draws a border on the left of the screen
            g.fillRect(588, 0, 12, 700); // draws a border on the right of the screen
        * Displays the array of bricks on the screen
        * @param  g   the Graphics object for this applet
        public void displayBricks(Graphics g)
            Brick currentBrick; // holds the brick data from the current ArrayList container
            for(int i = 0; i < 32; i++)
                currentBrick = (Brick)(brickArray.get(i)); // grabs the brick data from the current ArrayList container
                currentBrick.display(g); // displays the current brick
        * Called by the browser or applet viewer to inform this JApplet that it
        * should start its execution. It is called after the init method and
        * each time the JApplet is revisited in a Web page.
         public void start()
             if(timer == null)
                 timer = new Thread(this); // creates a new object of type Thread
                 timer.start(); // starts the new thread
                 running = true; // tells the program that the new thread is running
        * Runs the code that controls the animation
        public void run()
            do{
                repaint(); // redraws the screen
                try{
                    timer.sleep(100); // puts the thread to sleep for 100 milliseconds
                } catch(InterruptedException e) {running = false;}
                // !!!!!!! have tried placing ball.start() here
            } while(running);
            timer = null; // destroys the timer thread
        * Called by the browser or applet viewer to inform this JApplet that
        * it should stop its execution. It is called when the Web page that
        * contains this JApplet has been replaced by another page, and also
        * just before the JApplet is to be destroyed.
        public void stop()
            running = false; // tells the program that the thread is now done
    }These are the bits of code for my class heirarchy, just to (hopefully) make it easier to follow.
    import java.awt.*;
    * The parent class of all the games objects.
    * @author Kris Nelson
    * @version November 9, 2004
    public class Sprite
        protected double screenX, screenY; // stores the x and y location of the object
        * Constructor for objects of class Sprite
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        public Sprite(double xPosition, double yPosition)
            screenX = xPosition; // sets the initial x screen position
            screenY = yPosition; // sets the initial y screen position
        * Sets new x and y screen locations for an object
        * @param  newX   the new x screen location
        * @param  newY   the new y screen location
        public void setScreenXY(double newX, double newY)
            screenX = newX; // sets the new x screen location
            screenY = newY; // sets the new y screen location
        * Sends back the current x screen location
        * @return     the current x screen location
        public double getScreenX()
            return screenX; // returns the current x screen location
        * Sends back the current y screen location
        * @return     the current y screen location
        public double getScreenY()
            return screenY; // returns the current y screen location
    import java.awt.*;
    * Parent class of any game object that moves.
    * @author Kris Nelson
    * @version November 9, 2004
    public class MovingSprite extends Sprite implements Runnable
         protected double speedX, speedY; // stores the speed of an object in the x and y directions
         protected Thread timer; // the thread which controls animation for all moving objects
         protected boolean running; // tells the program whether or not the thread is running
         * Constructor for objects of class MovingSprite
         * @param  xPosition   the initial x screen position
         * @param  yPosition   the initial y screen position
         * @param  xSpeedValue   the speed in the x direction
         * @param  ySpeedValue   the speed in the y direction
         public MovingSprite(double xPosition, double yPosition, double xSpeedValue, double ySpeedValue)
              super(xPosition, yPosition); // passes the initial screen positions to Sprite
              speedX = xSpeedValue; // sets the speed in the x direction
              speedY = ySpeedValue; // sets the speed in the y direction
         * Sends back the speed in the x direction
         * @return     the speed in the x direction
         public double getSpeedX()
             return speedX; // returns the speed in the x direction
         * Sends back the speed in the y direction
         * @return     the speed in the y direction
         public double getSpeedY()
             return speedY; // returns the speed in the y direction
         * Starts the thread in order to start animation
         public void start()
             if(timer == null)
                 timer = new Thread(this); // creates a new object of type Thread
                 timer.start(); // starts the new thread
                 running = true; // tells the program that the new thread is running
         * Empty since the child objects have their own run methods
         public void run()
         * Stops the thread from running
         public void stop()
             running = false; // tells the program that the thread is now done
    import java.awt.*;
    * Creates a single ball who's purpose is to bounce around and destroy the bricks.
    * @author Kris Nelson
    * @version November 10, 2004
    public class Ball extends MovingSprite
        protected static final double BALL_WIDTH = 15; // sets the width of the ball
        protected static final double BALL_HEIGHT = 15; // sets the height of the ball
        * Constructor for objects of class Ball
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        * @param  xSpeedValue   the speed in the x direction
        * @param  ySpeedValue   the speed in the y direction
        public Ball(double xPosition, double yPosition, double xSpeedValue, double ySpeedValue)
            super(xPosition, yPosition, xSpeedValue, ySpeedValue); // passes the initial screen positions and ball speeds to MovingSprite
            // !!!!!!!! have tried placing timer.start() here
        * Displays a ball onto the screen
        * @param  g   the Graphics object for this applet
        public void display(Graphics g)
            g.setColor(Color.blue); // sets the balls color
            g.fillOval((int)(screenX), (int)(screenY), (int)(BALL_WIDTH), (int)(BALL_HEIGHT)); // displays the ball
        * Runs the code that controls the balls animation
        public void run()
            do{
                try{
                    timer.sleep(100); // puts the thread to sleep for 100 milliseconds
                } catch(InterruptedException e) {running = false;}
                screenX = screenX + speedX;
                screenY = screenY + speedY;  // this is VERY SIMPLE BALL MOVEMENT FOR TESTING PURPOSES, WILL BE CHANGED LATER
            } while(running);
    }Sorry if that was too much code. I'm just trying to make this easier to follow.
    I placed a // !!!!!!!!!!!!! comment in the places where I have tried starting the ball thread.
    So basically, everything is running fine, except that I'm not at all sure of where to start the ball Thread, and thus can't start anything moving. If someone could tell me where I should be starting the thread, I would REALLY appriciate it. Thank you :D
    - Kris

    Some advice.
    1. the start method on the ball should be called from the start method on the applet and should in turn call the start method on the sprite's thread.
    2. the run method of the Moveable sprite should have been declare abstract
    3. don't implement borders manually. There's a java.awt.Border class for that.
    4. probably, you don't want to have the game invoke each sprite by name; just make a big list of all the sprites and invoke all of them every time
    5. do you really need provision for a non-circular ball? this isn't rugby.
    6. I don't think you ever had a threading problem, just a display problem.
    7. Don't write comments like this:     ball.display(g); // displays the ballHere's my (even more simplified version):import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    * Class BreakoutApplet - Plays a simple game of Breakout.
    * @author Kris Nelson, modified by Michael Lorton
    * @version November 10, 2004
    public class BreakoutApplet extends JApplet implements Runnable {  
        protected Ball ball;
        protected Paddle paddle;
        public boolean running; // tells the program whether or not the thread is running
        protected Thread timer; // the thread which controls the animation for the applet
        public void init() {
            // this is a workaround for a security conflict with some browsers
            // including some versions of Netscape & Internet Explorer which do
            // not allow access to the AWT system event queue which JApplets do
            // on startup to check access. May not be necessary with your browser.
            getRootPane().putClientProperty("defeatSystemEventQueueCheck",
                                            Boolean.TRUE);
             ball = new Ball(this, GAMEWIDTH / 2, GAMEHEIGHT / 2, 5, 5);
        public final static int GAMEWIDTH = 600;
        public final static int GAMEHEIGHT = 400;
        public void paint(Graphics g) {
            g.setColor(Color.lightGray);
            g.fillRect(0, 0,
                       GAMEWIDTH, GAMEHEIGHT);
            ball.display(g); // displays the ball
        * Called by the browser or applet viewer to inform this JApplet that it
        * should start its execution. It is called after the init method and
        * each time the JApplet is revisited in a Web page.
        public void start() {
            if(timer == null) {
                timer = new Thread(this); // creates a new object of type Thread
                timer.start(); // starts the new thread
                running = true; // tells the program that the new thread is running
            ball.start();
        * Runs the code that controls the animation
        public void run() {
            do{
                repaint(); // redraws the screen
                try{
                    Thread.sleep(100);
                } catch(InterruptedException e) {running = false;}
            } while(running);
        public void stop() {
            running = false;
    abstract class Sprite {
        protected double screenX, screenY; // stores the x and y location of the object
        protected final BreakoutApplet parent;
        * Constructor for objects of class Sprite
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        public Sprite(BreakoutApplet parent, double xPosition, double yPosition) {
            this.parent = parent;
            screenX = xPosition; // sets the initial x screen position
            screenY = yPosition; // sets the initial y screen position
        * Sets new x and y screen locations for an object
        * @param  newX   the new x screen location
        * @param  newY   the new y screen location
        public void setScreenXY(double newX, double newY) {
            screenX = newX; // sets the new x screen location
            screenY = newY; // sets the new y screen location
        * Sends back the current x screen location
        * @return     the current x screen location
        public double getScreenX() {
            return screenX; // returns the current x screen location
        * Sends back the current y screen location
        * @return     the current y screen location
        public double getScreenY() {
            return screenY; // returns the current y screen location
        abstract public void display(Graphics g);
    * Parent class of any game object that moves.
    * @author Kris Nelson
    * @version November 9, 2004
    abstract class MovingSprite extends Sprite implements Runnable {
        protected double speedX, speedY; // stores the speed of an object in the x and y directions
        protected Thread timer; // the thread which controls animation for all moving objects
        protected boolean running; // tells the program whether or not the thread is running
        * Constructor for objects of class MovingSprite
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        * @param  xSpeedValue   the speed in the x direction
        * @param  ySpeedValue   the speed in the y direction
        public MovingSprite(BreakoutApplet parent,
                            double xPosition, double yPosition,
                            double xSpeedValue, double ySpeedValue) {
            super(parent, xPosition, yPosition);
            speedX = xSpeedValue; // sets the speed in the x direction
            speedY = ySpeedValue; // sets the speed in the y direction
        * Starts the thread in order to start animation
        public void start() {
            if(timer == null) {
                timer = new Thread(this); // creates a new object of type Thread
                timer.start(); // starts the new thread
                running = true; // tells the program that the new thread is running
        * Runs the code that controls the balls animation
        public void run() {
            while (parent.running) {
                try{
                    Thread.sleep(100);
                } catch(InterruptedException e) {
                    System.err.println(e);
                step();
        abstract protected void step();
    * Creates a single ball whose purpose is to bounce around and destroy the bricks.
    * @author Kris Nelson
    * @version November 10, 2004
    class Ball extends MovingSprite {
        protected static final int BALL_DIAMETER = 15;
        * Constructor for objects of class Ball
        * @param  xPosition   the initial x screen position
        * @param  yPosition   the initial y screen position
        * @param  xSpeedValue   the speed in the x direction
        * @param  ySpeedValue   the speed in the y direction
        public Ball(BreakoutApplet parent,
                    double xPosition, double yPosition,
                    double xSpeedValue, double ySpeedValue) {
            super(parent, xPosition, yPosition, xSpeedValue, ySpeedValue);
        * Displays a ball onto the screen
        * @param  g   the Graphics object for this applet
        public void display(Graphics g) {
            g.setColor(Color.blue);
            g.fillOval((int)(screenX),
                       (int)(screenY),
                       BALL_DIAMETER, BALL_DIAMETER);
        protected void step() {
                screenX = screenX + speedX;
                if (screenX < 0) {
                    screenX = -screenX;
                    speedX = -speedX;
                else if ((screenX + BALL_DIAMETER)> BreakoutApplet.GAMEWIDTH) {
                    screenX = 2*(BreakoutApplet.GAMEWIDTH  - BALL_DIAMETER) - screenX;
                    speedX = -speedX;
                screenY = screenY + speedY;
                if (screenY < 0) {
                    screenY = -screenY;
                    speedY = -speedY;
                else if ((screenY  + BALL_DIAMETER) > BreakoutApplet.GAMEHEIGHT) {
                    screenY = 2*(BreakoutApplet.GAMEHEIGHT - BALL_DIAMETER) - screenY;
                    speedY = -speedY;
    }

  • Help with systemd problems/reply to closed thread

    @Everyone; as the previopus topic was closed, I am opening a new one here, partly to reply to some things that was said to me in the previous thread/topic (and I do not like to leave people hanging), but mainly to try and get some help with my systemd config (that I was not able to find help with in the wiki or manpages).
    @czubek; eww, that sounds rather similiar to some other operating systems I've heard of (not just, but obviously including, windows)... For me, subjectively, that is not very attractive, as being able to have a single application do a single thing, and then mixing and matching as I personally see fit is a great thing.
    @tomegun: I can indeed see your point, but if I made direct quotes on all the things I reply too, my posts would reach biblical proportions.
    Mmm-hmm, I do indeed know of "the Arch Way"; however, the system that you expose can be of varying complexity as well, and I found that the system that was presented to me by way of Sysvinit/initscripts was a way simpler system than that presented to me by systemd.
    Indeed, and I do like that; I enjoy knowing how my system works and learning more about it; however, the truth is that reading manpages and the wiki isn't always enough. And I use the numbers instead of letters in certain places as a jest, please, do not get offended by that; if you have to, get offended by my opinions.
    Ah, I have now scanned the wiki, the manpages, and have already faced problems. While part of me is saddened by this fact (as I was hoping for a smooth transition to systemd), part of me is glad that I can at least prove that everything isn't quite as simple as some people would make it out to be. More on this later in this post, as I do need help with the problems I have faced.
    And I wouldn't say that the new and old way are equally trivial, as I immediatley faced problems with "the new way". More on this later.
    Ok, I find that if the debate is polarized, then there is nothing wrong with describing it as such. I spell what I see.
    Oh my... Ignored as a matter of principle? I would say that that is an excellent way to stagnate; by that logic, moviemakers, gamemakers etcetera should ignore any and all criticism they recieve, as the critics are not contributing.... Wouldn't that lead to a complete halt in development? Isn't criticism (so long as it is constructive, obviously) a key component of (media/software) evolution?
    Ah, I see, then I  misunderstood the current state of the install media
    "Some adjustements"... Well, I guess we'll have to see how that goes, then. Hopefully it'll be smooth.
    @Everyone; Awebb possesses stunning accuracy as far as his observations go.
    @zb3; My point exactly.
    @tomegun; I believe you to be wrong; complaining (but not whining) is the first step towards improvement, as I think that I and zb3 has shown.
    Further, your last point (where you talk about "deep understanding of Y" and whatnot) is basically saying that only devs and programmers can contribute, so zb3's observation would be correct.
    Also, making suggestions is part of constructive criticism; you can do that even if you can't code, e.g. by saying "X works badly because it makes Y crash; couldn't we replace X with something akin to Z?". This is a valid point even if you have no intricate understanding of X, Y or Z, and if it is impossible to replace X for one reason or the other, it's not hard to reply with "Replacing X is impossible because of reason Q", and then see if someone can solve reason Q etcetera.
    zb3's example is obviously helping; for one, it would allow people to know taht they can't boot with systemd in certain cases, or that installing/runing systemd can break their system. I would consider that rather important information.
    @Everyone; Now then, to see if I can (or rather, if I can get help to) shed some light on some problems I've been having.
    My transition to systemd went pretty smooth (besides the fact that I couldn't use 'systemctl' to set anything, and neither duckduckgo nor any posts in the forums could help me (the error I continously got was "Failed to issue method call: Launch helper exited with unknown return code 1") and that there are no manpages/tips on how to configure the files for "localtime" and "adjtime", which would've been good considering some syntax have changed) to about halfway through, to the point where I was supposed to start using systemd for my daemons.
    Now then, to the main problem; first, I tried running
    "systemctl enable syslog-ng.service"
    and got the following message;
    "ln -s '/usr/lib/systemd/system/syslog-ng.service' '/etc/systemd/system/syslog.service'
    ln -s '/usr/lib/systemd/system/syslog-ng.service' '/etc/systemd/system/multi-user.target.wants/syslog-ng.service'"
    Since it doesn't exclusively say that something went wrong (at least as far as I can understand), I pondered the message a bit, but moved on to try and start dbus by issuing
    "systemctl enable dbus.service",
    to which I got the reply
    "The unit files have no [Install] section. They are not meant to be enabled using systemctl."
    This I can only assume is an error message of some sort, especially seeing as it says "not meant to be enabled using systemctl", but the wiki rather explicitly states that that is what I am supposed to do.
    I dare not move on (or attempt to start other daemons) without further advice, as I fear I might break my system. Any ideas as to how to solve this would be greatly appreciated.

    tcmdvm wrote:
    The message;
    "ln -s '/usr/lib/systemd/system/syslog-ng.service' '/etc/systemd/system/syslog.service'
    ln -s '/usr/lib/systemd/system/syslog-ng.service' '/etc/systemd/system/multi-user.target.wants/syslog-ng.service'"
    indicates that running "systemctl enable syslog.service" is now enabled.
    If you try running sytemtctl enable <whatever>.service and get
    "The unit files have no [Install] section. They are not meant to be enabled using systemctl." means there is no <whatever>.service file available to enable.
    The dbus.service as far as I know is already enabled when installing systemd and doesn't require any action.
    Ah, right, systemd is chatty (I'm of the old skool; if nothing is/goes wrong, a program should keep quiet).
    Oh ok, then I should dare more on.
    ZekeSulastin wrote:To be a bit more precise, it means the service is there but it's only used as a dependency for something else; the [Install] section of the file is what tells systemctl where to link it and such.  Also, where exactly in the wiki were you told explicitly to 'systemctl enable dbus.service'?  I can easily point you to the sections in both installation guides that tell you how to set things like /etc/localtime et. al (also `man 7 archlinux`), but not the one that said to manually enable dbus.
    Ah, I see; and well, I was told right here, going from the top, to "Enable Daemons formerly listed in rc.conf [...] For a translation of the daemons from /etc/rc.conf to systemd services, see: List of Daemons and Services.", and, using the list, dbus is mentioned there, as you can see. Since I started from the top, I did not know that you didn't need to enable that service. Perhaps it could be added to the descriptions of the relevant services in the Wiki which ones are autostarted?
    ZekeSulastin wrote:Lastly, I don't think trying to continue conversations from a closed thread is a very good idea, let alone doing it in a giant undivided wall of text that makes it quite difficult to pick out much any single topic.
    Meh, I directly refer to the relevant people, they can easily see their own old posts in the previous thread, etcetera... I think te ones who have something to say will be able to find my replies to their previous statements (or so I hope). For now, as everyone can see, I quote stuff (but man might I make some huge posts if I ever post again in the future, if I quote what I reply to).
    fsckd wrote:This is not really a technical support subforum. Moving from Arch Discussion to Newbie Corner.
    Ah ok, thanks (or perhaps a cautious thanks? Moving it to "newbie corner" might, after all, be a subtle insult...).
    tomegun wrote:It is not really possible to follow your message as you don't quote what you are replying to. Moreover, as the thread was closed I think that means we should stop the discussion ;-)
    Hmm, I think it means cop-out for lack or proper arguments/responses... But ok, I'll let it slide, for now (mainly as I can't do much else).
    tomegun wrote:You are not meant to enable dbus.service as it is enabled unconditionally. To check the enabled/disabled state of your services try "systemctl list-unit-files". "static" means that you are not supposed to enabled/disable it.
    Ah ok, thank you. Now, having abandoned all hope, I'll start configuring again and see how it goes... May the void protect me. If I die, grieve not for me, but remember me in the fight against hard-to-configure applications.
    (edit/addon)
    Actually, what am I supposed to do with "hwclock"? the List of Daemons only says that I shouldn't run that in tandem with ntpd, but I'm not running ntpd, so... How do I get hwclock with systemd?
    Edited for additional question.
    Last edited by incassum (2012-11-07 08:44:42)

  • Help with Java Threads

    Hello,
    Can anyone help with what I'm trying to do:
    I would like to create a thread such as:
    Database connection successful....
    where the '...' keep moving up. So as long as there is a database connection the '...'s should keep moving like so:
    ...... then back to:
    Does that make sense?
    Thanks
    am328

    What you want to do if really very simple...
    Why don't you first write a simple loop that generates your '.'s. Once you get that working, wrap the loop inside a thread that checks for a database connection.

  • Help with running multiple threads

    I'm new to programming with threads. I want to know how to run
    multiple threads at the same time. Particularly for making games
    in Java which I'm also begining to learn. For running multiple
    threads at the same time, do you have to put two run() methods
    in the source? If not then how do you make two threads or more
    run at the same time?
    Thanks for helping.

    For running multiple
    threads at the same time, do you have to put two run()
    methods
    in the source? Hi there,
    Each thread is presumably performing a task. You may be performing the same task multiple times or be performing different tasks at once. Either way, each task would typically be contained within the run() method of a class. This class would either be a subclass of java.lang.Thread (extends Thread) or would be an implementation of java.lang.Runnable (implements Runnable). In either case, you would define a method with signature (public void run()...). The difference comes into play when you wish to actually perform one of these tasks. With a subclass of Thread, you would simply perform:
    new MyTask().start();
    With an implementation of Runnable, you would do this:
    new Thread(new MyTask()).start();
    This assumes you don't need to monitor the threads, won't be sending any messages to your tasks or any such thing. If that were the case, you would need to tuck away those returns to new MyTask() for later access.
    In order to launch two threads simultaneously, you would have something along the lines of:
    new MyTask().start();
    new MyOtherTask().start();
    Now it is perfectly possible that MyTask() would complete before MyOtherTask() managed to start in which case it wouldn't appear as if you had actually had multiple threads running, but for non-trivial tasks, the two will likely overlap. And of course, in a game, these tasks would likely be launched in response to user input, which means that you wouldn't have any control over when or in what order they executed.
    Anyhow, it's as simple as that. You should also consider following the Java Threading trail which shows a simple example of using multiple threads. You can find it at:
    http://java.sun.com/docs/books/tutorial/essential/threads/index.html
    Regards,
    Lynn

Maybe you are looking for