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.

Similar Messages

  • Java threading problem... threads only work on 1 processor

    I've got a iterative deepening problem that i have to parallelize. As far as i know i did everything correctly however everything seems to be running on 1 processor instead of 2 processors. As far as i know i am using threads (-Xprof either defines them as thread-1 thread-2 or pool1-thread1,depending on the method used for issueing)
    the worker thread is:
    public int solutionsT(Board board, int currentDepth) {
            int temp = 0;
            int result = 0;
            if (board.distance() == 0) {
               return 1;
            if (board.distance() > board.bound()) {
                return 0;
            Board[] children = board.makeMoves();
            result = 0;
            for (int i = 0; i < children.length; i++) {
                if (children[i] != null) {
                    temp = solutionsT(children, currentDepth + 1);
    if(temp != 0){
    result += temp;
    return result;
    public void run() {
    int temp =0;
    int i = 0;
    while(true){
    while(bag.size() !=0){
    bag.putSolution(solutionsT(bag.get(),1));
    try{   
    barrier.await();
    }catch(Exception e){}
    it get's it's input from a bag that is filled before the iteration begins. (once the bag is filled it trips a barrier) this worker thread is a implementation of Runnable
    This piece of code is used to make the thread object and to issue it
    public SolutionThread(int numberOfThreads) {
       thread = numberOfThreads;
       bag = new bagOfBoards();
       barrier = new CyclicBarrier(thread+1);
       if(thread > 1){
          ExecutorService threadExecutor = Executors.newFixedThreadPool( thread );
          solution = new ThreadTest[thread];
          bag = new bagOfBoards();
          for(int i = 0;i<thread;i++){
             solution[i] = new ThreadTest(bag, lock, barrier, i);
             threadExecutor.execute(solution);
    finally this is the code which is used to acces the bag and get a board.
    synchronized public Board get() {
                if (size > 0) {
                size--;
                Board result = bag[size];
                return result;
            } else {
             return null;
        }since this method is synchronized and it always returns something (either null or a board) and the worker tests for this. there is no race condition here.
    furter more. the main thread is a loop. It fills te bags with an intial state. then it trips the barrier and waits for the workers to do the work. the workers then process the bag until it hits zero and then trip the barrier so that the main thread can do the next iteration (and fill the bag)
    p.s. i know the code is a bit messy, but i want to get the threading to work. As of now i relaly don't understand why the threads are just running on 1 processor instead of 2 processors. not only that. the excecution time is nearly the same as that of a sequential equivalent.
    p.s.2 the code is parallisable. and it is run on a smp system.
    Message was edited by:
    jstrike

    i'm very sure that the jvm and os support smp. the
    problem really should be in the code.I don't see how this can be the case. There's nothing in the Java language that deals with how threads are assigned to processors (at least not as far as I know) so there isn't anything you can do in your code to affect that.
    Or did you meant that i have to tell the jvm in the class that
    there is support for multiple processorsThat would be the only possibility. I have no idea whether it can be done or not, though.

  • Sun Java System Web Server 6.1 SP3 service-j2ee threads problem

    Hi,
    Sorry my english.
    I'm an intermediate Java programmer and a newbie in
    the Sun's web servers world.
    I'm doing an evaluation of an web applicaction
    written in Java Servlets that is
    supposed to have a leaking threads problem. We use
    SunOS 5.9 (... sun4u sparc SUNW,UltraAX-i2) and
    JVM 1.5 Update 4 (the problem is presented too
    in SunOS 5.8 and JVM 1.4.2_04).
    We have seen, thanks to 'prstat' (PROCESS/NLWP) a
    increasing thread's growing in one of the process
    that correspond to our web server instance (I'm sure I'm
    looking the right process). I have checkout the source
    code and it seems like the app doesn't have threads
    problems. I have used the Netbeans Profiler and I see a
    high number of threads called service-j2ee-x that grows
    in congestion moments and never disappear.
    Anybody could help me with suggestions?
    Thank you very much.

    Elvin,
    Thankyou, yes I am unfamiliar with debugging Java apps. I got the web server Java stack trace and I have passed this on to the developer.
    The web server finally closes the socket connection after the total connections queued exceeds 4096.
    There are several hundred entries like this... waiting for monitor entry.. could be a deadlock somewhere?
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: "service-j2ee-506" prio=5 tid=0x04b62a08 nid=0x17a waiting for monitor entry [dd74e000..dd74f770]
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at com.verity.search.util.JSDispenser.getConnResource(Unknown Source)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: - waiting to lock <0xe979b2b0> (a com.verity.search.util.JSDispenser)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at com.verity.search.DocRead.getDoc(Unknown Source)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at com.verity.search.DocRead.getDoc(Unknown Source)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at com.verity.search.DocRead.docViewIntern(Unknown Source)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at com.verity.search.DocRead.docView(Unknown Source)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at au.com.relevance.viewDoc.PdfXmlServlet.performRequest(PdfXmlServlet.java:120)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at au.com.relevance.viewDoc.PdfXmlServlet.doGet(PdfXmlServlet.java:141)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at javax.servlet.http.HttpServlet.service(HttpServlet.java:787)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at javax.servlet.http.HttpServlet.service(HttpServlet.java:908)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.core.StandardWrapperValve.invokeServletService(StandardWrapperValve.java:771)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:322)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:212)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:209)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at com.iplanet.ias.web.connector.nsapi.NSAPIProcessor.process(NSAPIProcessor.java:161)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at com.iplanet.ias.web.WebContainer.service(WebContainer.java:580)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at com.iplanet.ias.web.WebContainer.service(WebContainer.java:580)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: "StandardManager[highlight]" daemon prio=5 tid=0x000f3530 nid=0x1e waiting on condition [e15ff000..e15ffc28]
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Thread.sleep(Native Method)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.session.StandardManager.threadSleep(StandardManager.java:800)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.session.StandardManager.run(StandardManager.java:859)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Thread.run(Thread.java:534)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: "WebappLoader[highlight]" daemon prio=5 tid=0x000f3328 nid=0x1d waiting on condition [e16ff000..e16ffc28]
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Thread.sleep(Native Method)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.loader.WebappLoader.threadSleep(WebappLoader.java:1214)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.loader.WebappLoader.run(WebappLoader.java:1341)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Thread.run(Thread.java:534)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: "StandardManager[]" daemon prio=5 tid=0x000f2b08 nid=0x1c waiting on condition [e1b7f000..e1b7fc28]
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Thread.sleep(Native Method)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.session.StandardManager.threadSleep(StandardManager.java:800)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.session.StandardManager.run(StandardManager.java:859)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Thread.run(Thread.java:534)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: "WebappLoader[]" daemon prio=5 tid=0x000f2900 nid=0x1b waiting on condition [e1c7f000..e1c7fc28]
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Thread.sleep(Native Method)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.loader.WebappLoader.threadSleep(WebappLoader.java:1214)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.loader.WebappLoader.run(WebappLoader.java:1341)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Thread.run(Thread.java:534)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: "StandardManager[sitesearch]" daemon prio=5 tid=0x000f1cd0 nid=0x1a waiting on condition [e23ff000..e23ffc28]
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Thread.sleep(Native Method)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.session.StandardManager.threadSleep(StandardManager.java:800)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.session.StandardManager.run(StandardManager.java:859)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Thread.run(Thread.java:534)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: "WebappLoader[sitesearch]" daemon prio=5 tid=0x000f1ac8 nid=0x19 waiting on condition [e24ff000..e24ffc28]
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Thread.sleep(Native Method)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.loader.WebappLoader.threadSleep(WebappLoader.java:1214)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.loader.WebappLoader.run(WebappLoader.java:1341)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Thread.run(Thread.java:534)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: "StandardManager[search]" daemon prio=5 tid=0x000f0a88 nid=0x18 waiting on condition [e317f000..e317fc28]
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Thread.sleep(Native Method)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.session.StandardManager.threadSleep(StandardManager.java:800)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at org.apache.catalina.session.StandardManager.run(StandardManager.java:859)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Thread.run(Thread.java:534)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: "Signal Dispatcher" daemon prio=10 tid=0x000ef840 nid=0x12 waiting on condition [0..0]
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: "Finalizer" daemon prio=8 tid=0x000ef638 nid=0x10 in Object.wait() [fa27f000..fa27fc28]
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Object.wait(Native Method)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: - waiting on <0xe917fb10> (a java.lang.ref.ReferenceQueue$Lock)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:111)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: - locked <0xe917fb10> (a java.lang.ref.ReferenceQueue$Lock)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:127)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: "Reference Handler" daemon prio=10 tid=0x000ef430 nid=0xf in Object.wait() [fa37f000..fa37fc28]
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Object.wait(Native Method)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: - waiting on <0xe917fb78> (a java.lang.ref.Reference$Lock)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.Object.wait(Object.java:429)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:115)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: - locked <0xe917fb78> (a java.lang.ref.Reference$Lock)
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: "main" prio=5 tid=0x000ee3f0 nid=0x1 runnable [0..ffbff200]
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: "VM Thread" prio=5 tid=0x004ee328 nid=0xe runnable
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: "VM Periodic Task Thread" prio=10 tid=0x004ee5d0 nid=0x16 waiting on condition
    [15/May/2006:22:01:51] warning ( 3196): CORE3283: stderr: "Suspend Checker Thread" prio=10 tid=0x004ee548 nid=0x11 runnable
    [15/May/2006:22:15:10] failure ( 3196): HTTP3287: connection limit (4096) exceeded, closing socket

  • Problems with java Thread

    I'm reading book "JAVA THREAD" published by OREILLY.
    And on fifth chapter, it gives an example.
    one Thread's two method:
    private boolean done = false;
    public void run()
    while(!done)
    foo();
    public void setDone()
    done = true;
    it says, the run method will be compiled as machine code:
    Begin method run
    load register r1 with memory location 0xff12345
    Label L1:
    Test if register r1 == 1
    If true branch to L2
    Call method foo
    Branch to L1
    Label L2:
    End method run
    setDone method will be compiled like:
    Begin method setDone
    Store 1 into memory location 0xff12345
    End method setDone
    And it says " because Run method will never reload 0xff12345 to register r1(in while loop), so setDone method will never lead to run stop.
    I'm so puzzled with this. I have test this code on windows platform, run method can stop after another Thread call setDone method !.
    but I think "JAVA THREAD" should have error on this, so why ?

    If the book says it will happen like that, then the book is wrong.
    I think what they meant--and what would be correct to say--is that that is an example of what could happen if you don't synchronize all access to the run variable.
    The point is this: Threads can have local copies of variables, that are separate from other threads' local copies and separate from the "master" copy. The spec doesn't define where those local copies live--the implementation can put them anywhere it wants--but the most natural and sensible thing would be to store the local copies in CPU registers, rather than in main mem.
    The example the book gave shows what might happen if that VM stores threads' local copies in registers. There's no guarantee that the problem they described will happen, but it could, so you have to guard against it.
    You guard against it by declaring that shared variable volatile, which requires that the threads use the master copy rather than their local copies, or by synchronizing every access to that thread. Syncing requires reading from the master copy on entering the sync block (or on first access) and writing out to the master copy upon leaving the sync block.

  • A blocking problem of java thread.

    Hi!
    I would like to execute native thread concurrently in the Java Native Interface.
    When a Java thread called a native thread to use java native interface, Java thread is blocking for processing native thread.
    So, other java threads don't execute because they are blocking.
    Why do these problems occur at JVM(personal basis profile:CVM)?
    Regard.
    Message was edited by:
    peeppeep

    you need to explaing the problem more clearly, maybe post the code?

  • Java Threads not being released after loggin off

    Hello everyone,
    We are seeing a weird problem in our PI 7.0 box.
    Once I logout from the XI box (both ABAP and Java stck) my basis tem still sees Java threads aginst my id still open. Our system does not seem to be realeasing Java threads.
    Is this a know problem? What are the remidition steps.

    Hi,
    Are there existing HTTP sessions only?
    The following might be helpful.
    http://help.sap.com/saphelp_nw73/helpdata/en/c7/5ee440ba994fa3b187ff2f050cfe7c/content.htm
    http://wiki.sdn.sap.com/wiki/display/ERPHCM/Sessionnotendingafterlogoff
    Regards,
    Varun

  • Java threads monitoring

    I am using Java threads in my Java program, running on Windows Professional 2000. I am monitoring the threads using Windows Performance Monitor (WPM). However, even running a small Java program which creates only 2 threads, results in many (at least 10) instances of Java threads being reported by the WPM. Problem is, in WPM, there is no way to determine which threads in the WPM are the threads that I programmatically created. Any ideas on how to determine this?
    Thanks.
    Rhodie

    Hi Dmirty ,
    To handle large asynchronous message   in queues you can use  message packaging where multiple message are processed in one package . to make it applicable you have to perform these simple steps
    1. go to SXMB_ADM add one RUNTIME parameter PACKAGING and value 1
    2 GO TO transaction SXMS_BCONF set delay time 0 message count 100 messages and package size 1000 KB
    with these setting your improvement will increase .secondly also put  IN SXMB_ADM monitor category parameter QRFC_RESTART_ALLOWED TO 1
    this will automatically start your queue . Only thing you have to take care if you enable packaging them don't keep too many parallel queue i.e EO_INBOUND_PARALLEL and EO_OUTBOUND_PARALLEL should be less than 20
    Regards,
    Saurabh

  • Cant syncronize! Threads problem

    Hello everybody,
    recently i posted a question(im new to threads) and it was asked immediately but now i have another
    type of problem.
    Please read here the initial post and the answer and please give me any ideas..
    Initial Post
    Hi everybody,i have this thread problem(i'm new to java and h
    ave no idea what exactly to do).
    Well,in my applet i have this action performed method
    that i imagine is in the event dispatch thread.
    This method calls as u see, two other methods of a class named CPU(.
    Note that fetch and execute are observed classes and my applet class
    is the observer.
    The problem is that during the execution of fetch() and execute(),
    inside these methods change some things and so they call notifyObservers(Object arg)
    passing to the applet the argument and so the applet updates some text components.
    But as you can immagine there is no time for the gui to update himself so i see nothing.
    So, my question is which of the methods need to be in a separate thread so to ensure
    visible results(component updating)?
    Perhaps,the update method needs to be invokedLater with SwingUtilities?
    Please give me an example code if possible.
    Here is the actionPerformed code(from the applet class) and the fetch method:
        void executeProgramButton_actionPerformed(ActionEvent e) {      
    int numInstr = this.machine.ram.segmentSize;       
    for (int i = 0; i < numInstr; i = i + 4) {           
    machine.cpu.fetch();           
    machine.cpu.execute();       
    /*The following method is in the CPU class
    fetch method:here the observedPC is the observable value
    that notifies the observer(the main applet)
    that does: pcTextField.setText(arg.toString());*/   
    public void fetchInstructionProgram() {       
    observedPC = Integer.toString(pc);       
    setChanged();       
    notifyObservers(observedPC);       
    instructions++;       
    instruction=readOperation(cache.instructionfetch,pc);       
    pc = pc + 4;    }
    Answer to initial post
    Author: stevejluke
    One way could be to put the content of the action performed method into a new thread, then use invokeLater in your Observers that cause GUI updates:
        void executeProgramButton_actionPerformed(ActionEvent e) {     
    new Thread()       {      
    public void run()        {         
    int numInstr = this.machine.ram.segmentSize;         
    for (int i = 0; i < numInstr; i = i + 4)           {           
    machine.cpu.fetch();           
    machine.cpu.execute();         
    }.start();    }
    // In your Observer    public void update(Observable o, Object arg)    {     
    SwingUtilities.invokeLater(new Runnable() {      
    public void run()        { 
    /* your GUI afecting code
    });[i]
    Or something like that.
    You might need to watch for synchronizing things
    He was right...GUI is responsive but the results...
    Well,let me describe the new problem.
    Here you cant see the method execute().
    The problem is a synchronization problem.
    Actually,what the two methods do is:fetch() updates the value of a long called instruction and execute() takes this value and do some things.Note also that the time the execute method needs to finish is not
    always the same.By that, i mean that it depends on the value of the instruction updated by fetch().
    By putting some System.outs before and after updating i realized that there are delays or sometimes
    i noticed that fetch() executes 2 times before execute() takes control.
    So,i created some synchronized private methods set and get to control access to these resources.
    Better but still not correct...
    What should i look?Where stays the answer?
    How to synchronize these two methods on these resources?
    Thank you in advance,
    Chris

    I think that your fetch and execute has a "Producer-Consumer Relationship"
    in such cases you can make the producer place the produced value in to a queue and consumer take the vlues from the queue
    In the producer thread it sleeps for a while and try again if the Queue is full
    In the Consumer thread it sleeps for a while if the Queue is empty and then try again
    Or you can do as follows
    In the Producer thread it waite() if the Queue is full
    In the Consumer thread it waite() if the queue is empty
    When ever Producer put a value in to the Queue it calls the notify on Consumer and when ever Consumer takes a value from Queue it calls the notify() on Producer
    you can even use notify all
    I think thiere is no built in Queue class in java so you will have to write one here is a example
    public class MyLongQueue{
                long data[];
                int head, tail;
                int size;
               public MyLongQueue(int size){
                    data = new long[size];
                    head = -1;
                    tail = -1;
                    this.size = 0;
                public synchronized boolean isFull(){
                    return (size==data.length);
                public synchronized boolean isEmpty(){
                    return (size==0);
                public synchronized boolean  insert(long l){
                    if (size==data.length) return false; //Queue is full cant add more data
                    tail = (tail + 1) % data.length;
                    data[tail] = l;
                     size++;
                    return true;
               public synchronized long remove(){
                   if (size==0) throw new ArrayIndexOutOfBoundsException();
                   size--;
                   head = (head + 1) % data.length;
                   return data[head];

  • Multiple Threads Problem

    Hi,
    I am new to Java Threading and the current program that I am working is having problems. The program basically paints lines and dots or onto a JPanel which displays an image. There exists a thread here to suspend and resume the drawing at the user's disposal. This part works flawlessly.
    Now since the images are quite large I have attempted to add a JWindow to the JFrame to indiate that the image is loading. And here lies my problem, the JWindow which also contains a paint method does not display anything until after the image is fully loaded onto the JPanel.
    Can someone please tell me what I am doing wrong and how to implement this?
    Thanks, James
    Here is how my program is structured:
    public class Proj extends JFrame
    public Proj()
    Display disp = new Display();
    Thread thr1 = new Thread(disp);
    thr1.start();
    Container con = getContentPane();
    con.add(vsr);
    setSize(500,500);
    show();
    public static void main(String [] args)
    {  new Proj();
    class Display extends JPanel implements Runnable
    public Display()
    Loading ld = new Loading();
    Thread thr2 = new Thread(ld);
    ld.start();
    // gets data and image files
    ld.interrupt();
    public void paintComponent(Graphics g)
    // draws image, lines, circles etc.
    public void run()
    // involved with data to draw next image, lines etc.
    class Loading extends JWindow implements Runnable
    public void paint(Graphics g)
    // displays loading animation
    public void run()
    // animation code

    Since Swing is single-threaded, any painting activity after a component is realized/visible should be handled on the EDT (Event Dispatch Thread). The loading of data/files can be done on worker different thread. On the EDT you should fetch the status and paint your progress bar. If you paint the progress bar on the worker thread it would not work out the way you want. Try to also investigate into SwingUtilities.invokeLater method which allows us to put a code to be executed on the EDT.

  • Java thread not working in windows 7

    I have a Java app that runs just fine on Windows XP. However, on Windows 7 there is a problem related to a job being done via a Java thread.
    Background: The app spawns a separate job via a Java thread and continues on while the spawned job executes. In other words, 2 things happen at once.
    Problem: On Windows 7, when the app spawns the job, Windows sits and waits for the spawned job to complete before it continues on. In other words, 2 things DO NOT happen at once.
    It's as if Java threading does not work in Windows 7. Any input would be greatly appreciated. Thanks.

    l_sleven wrote:
    Thanks for the input, guys. From now on I'll be sure to include a SSCCE.
    I'm beginning to believe this is actually my ignorance of threading in SWT, and XP was more forgiving than 7.
    I would include a SSCCE, but of the 4 different ways I tried to get this to work I wouldn't know which to include since all failed to fix the problem.
    If you want to identify a link to a web page identifying 'best practices' for SWT threading, that would be great. Be aware though that there's a good chance I've already googled the page.
    A programmer smarter than me once said, "The road to best practices is a bumpy ride".[Concurrency in Swing|http://download.oracle.com/javase/tutorial/uiswing/concurrency/index.html]

  • I want to execute other java thread in the JNI.

    Hi!
    I would like to execute other java native thread concurrently in the Java Native Interface.
    When a Java thread called a native thread to use java native interface, Java thread is blocking for processing native thread.
    So, other java threads don't execute because they are blocking.
    Why do these problems occur at JVM(personal basis profile:CVM)?
    I hope you explain this reason in detail.
    Regard.
    Message was edited by:
    peeppeep

    Cross post
    http://forum.java.sun.com/thread.jspa?threadID=786857&messageID=4471999#4471999

  • How to terminate a java thread from c++ code?

    Hi,
    I made a screensaver which loads a jvm, forks a thread running a java class, wait until user's action(i.e. mouse move/click keyboard input), then terminate the java thread.
    However, I met a problem, How to terminate a running java thread from c++ code?
    Here is my code, but it does not work: (even after the terminate is called, jvm throws an error)
    JNIEnv* env;
    JavaVM* jvm;
    HANDLE hThread; //handle for the startThread
    unsigned __stdcall startThread(void *arg)
         jclass cls;
         jmethodID mainId;
         jint          res;
         int threadNum = (int)arg;
         res = jvm->AttachCurrentThread((void**)&env, NULL);
    cls = env->FindClass( MAIN_CLASS);
         mainId = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");
         // setup the parameters to pass to main()
         jstring str;
         jobjectArray args;
         int i=0;
         args = env->NewObjectArray(1, env->FindClass("java/lang/String"), 0); //only one input parameters
         str = env->NewStringUTF("localhost");
         env->SetObjectArrayElement(args, 0, str);
         env->CallStaticVoidMethod(cls, mainId, args); // call main()      
         if (env->ExceptionOccurred()) {
                   env->ExceptionDescribe();
         return TRUE;
    Here is the main method:
    First create the jvm and load the thread. then tries to terminate the thread, but failed here
    switch (msg)
    { case WM_CREATE:
              JavaVMOption options[NUMBEROFOPTIONS];
              JavaVMInitArgs vmargs;     
              jint rc;
              vmargs.version = JNI_VERSION_1_4; /* version 1.4 */
              vmargs.options = options;
              vmargs.nOptions = NUMBEROFOPTIONS;
              vmargs.ignoreUnrecognized = JNI_FALSE;          
              rc=JNI_CreateJavaVM( &jvm, (void **)&env, &vmargs ); /* create JVM */
              /* We pass the thread number as the argument to the invoked thread */
              unsigned int threadId = -1;
              // to initialize a thread-safe C runtime library
              hThread = (HANDLE)_beginthreadex(NULL, 0, &startThread, NULL, 0, &threadId );
    } break;
    case (WM_DESTROY):
              CloseHandle( hThread );
              jvm->DestroyJavaVM(); /* kill JVM */
              Debug("Destroy Java Virtual Machine\n");
    }break;
    Note, after the thread "startThread" runs, it has an infinite loop and will not terminate, until the user clicks to terminate.(I didn't call jvm->DetachCurrentThread();_endthreadex(0); in the "startThread" because the java thread will not terminate by itself)
    Thus, the only way to terminate the thread is to call closehandle(hthread) in the main thread, which may cause jvm to throw an error.
    Do you know how to terminate a java thread safely???
    Thanks a lot

    Assuming that your java thread is in a loop of some kind. Such as
    int i=1; /* I tried using a boolean, I just could not get my C++ env, to change this value. So i decided to use an int */
    run {
    while(i)
    isdfjsdfj
    void seti()
    i=0
    So, B/4, i call destroyVM in my C++ code, i call this seti(). so the loop terminates, therefore my thread finishes executing and ends.
    Hope this helps
    tola.

  • Multiple java threads in a JVM created by the invocation interface

    Hi,
    I have a certain application APP that calls functions of a C library. One of these functions creates a JVM through the invocation interface. In the JVM I create some other threads and a Swing GUI. From the java "main" thread as well as the other threads (including the Swing event dispatcher thread) I need to call dll functions through native java methods. The latter indirectly (through another dll) invoke functions of an API of application APP.
    I have problems when making calls from the java threads to the java native library. In some cases everything works well i.e., I'm able to make calls to the java native library from both the "main" java thread and the other threads. In other cases a crash occurs when attempting to access the native library from any threads but the "main" thread.
    Can anyone help me on this? Is there any requirement that only the main java thread makes callbacks to C code?
    Thanks.

    > why later sets of java application is taking longer?
    Probably because of CPU usage.  But could be memory.
    >Can I do something here so that later sets of apps also completes in 3 mins
    You tune the task, the complete task, to the box.  That means you must understand in detail what is taking time and then architect that to make the best use of the available CPUs and memory (and other resources as used by the task.)

  • JNI & thread problem

    Folks,
    I am using JNI to access WIA (Windows Image Acquisition) functionality under MS Windows XP. WIA consists of a bunch of COM interfaces. I have several native functions in a single dll, with a limited number of static variables stored in the dll between calls. This all works fine as long as long as the calls occur from the same java thread, but not if a new thread is created for some of the calls. I.e., this works:
    final WIACtrl ctrler=new WIACtrl();
    ctrler.initializeWIA();
    ctrler.transferJPGNative("0001\\Root\\IMG_0087","c:\\test.jpg");
    but this does not:
    final WIACtrl ctrler=new WIACtrl();
    ctrler.initializeWIA();
    (new Thread() {
    public void run() {               
    ctrler.transferJPGNative("0001\\Root\\IMG_0087","c:\\test.jpg");
    }).start();
    Here, initializeWIA() and transferJPGNative() are the native methods. What happens in the second case is that transferJPGNative fails in one of the COM methods (not the first COM method it calls). The COM method returns an HRESULT indicating an error (509) which I can't find using any of the usual MS error look-up mechanisms. (Admittedly I am not the world's greatest Windows programmer...)
    Anyway, any suggestions would be much appreciated. I have found some issues regarding JNI and threads in this forum's archives, but none of them seem to apply to quite this situation.

    As a guess this is just a windows threading problem.
    And with COM you have to do things differently (I believe) if there is more than one thread. You might not even be allowed to do it with for that particular API.
    It could also be that you are initializing things more than once. Or you need to initialize twice (two handles.)
    At any rate you could always fix it by making the java code only allow calls for a single thread.

  • Help calling JNI function from a java thread

    I am using the following code to call a JNI fuction from a java thread:
    public class CMSMessageHandler extends MessageHandler{
    static{
    System.loadLibrary("jastb");
    public native int cmsReadIt(ByteBuffer buff);
    private ByteBuffer dirbuf = null;
    /** Creates a new instance of CMSMessageHandler */
    public CMSMessageHandler() {
    // allocate to max size datagram
    dirbuf = ByteBuffer.allocateDirect(65536);
    public void readMessages(){
    /*Thread worker = new Thread(){
    public void run(){*/
    int count;
    while (true){
    try{
    count = cmsReadIt(dirbuf);
    } catch (Exception e){
    e.printStackTrace();
    worker.start();*/
    public static void main(String[] args) {
    CMSMessageHandler handler = new CMSMessageHandler();
    handler.readMessages();
    When I run this main method with the thread commented out, it works great. When I run the main method with the thread, it works great for a while, and then funny things start happening with the native library I am using. My native library uses shared memory, signals, and semaphores. It feels a bit like my java program is stomping on the resources that my native library is using, when a run the java program with a thread.
    Is there something I don't know about calling native code from a thread? Should I be doing something explicitly to protect my native library's shared memory, signals, or semaphores?
    Thanks,
    Lisa.

    Does the library do any initialization when loaded? Does it make a dangerous assumption that the thead calling cmdReadIt will always be the same thread that initially loaded it? Try loading the library in the worker thread instead of in the main thread via the static initializer.Yes. There is a call to another native method cmsOpenIt that does CMS initialization. I put cmsOpenIt as well as the System.loadLibrary("jastb") in the worker thread and I'm still experiencing the same problems.
    Incidently, the mere presence of another Thread in this program does not seem to cause problems. It's only when I run calls to cmsReadIt in a thread that I get into trouble.
    For example, this works fine:
    public class CMSMessageHandler extends MessageHandler{
        public native int cmsReadIt(ByteBuffer buff);
        public ByteBuffer dirbuf = null;
        static {
            System.loadLibrary("jastb");
        public CMSMessageHandler() {
            // allocate to max size datagram
            dirbuf = ByteBuffer.allocateDirect(65536);
        public void readMessages(){
            try{
                int count = 0;
                while (true){
                    count = cmsReadIt(dirbuf);
            } catch (Exception e){
        public static void main(String[] args) {
            CMSMessageHandler handler = new CMSMessageHandler();
            Thread worker = new Thread(){
                public void run(){
                    while (true){
                        try{
                            Thread.currentThread().sleep(1000);
                            System.out.println("sleep thread.");
                        } catch (Exception e){
                            e.printStackTrace();
            worker.start();
            handler.readMessages();  
        }Are there JVM flags that I should experiment with that might help mitigate/diagnose this problem?

Maybe you are looking for

  • How to install XP drivers for Bootcamp on Mac OSX v 10.6.7?

    I installed Windows XP Porfessional SP3 on my Bootcamp partition but when I insert the "Software Support" DVD that my Mac created it says that I have to be running Windows 7 only and does not install any drivers. I have been pulling my hair out tryin

  • Deletegate permissions in AD

    Hello Team, I see how to delegate control to a user to manage an OU with the settings "Create, delete, and manage user accounts".  Is there a way to have that user only "mange" user account settings without the create and delete permissions...? Tom K

  • 3 flat files grouped into 1 flat file

    Hi XI Gurus! IS there a way to merge the contents of all 3 flat files (source) to 1 flat file without using BPM? And IF I have to use BPM, could you please give me a general idea on how I can go on about it? After merging, I have to map the fields to

  • Cairngorm & Problems with Shared Components

    Thanks in advance for any help. I still consider myself a newbie, so please excuse any stupid errors that I make in describing the problem I am having. I am working on a Cairngorm app, the framework of which has been handed to me. I have a component

  • Significance of CRMSUBTAB and CRMFILTAB?

    HI friends what is the significance of CRMSUBTAB and CRMFILTAB? what is the need of Number ranges in filter settings? Regards Vinny Edited by: vinny novice on Nov 25, 2008 5:32 AM