Multiple Runs of Thread Problem

hello friends ,
i have the following code where there are two threads and they will execute simultaneously
but the error is
<code>
import java.util.*;
import java.lang.*;
class Demo1.java extends Thread
public void run()
for (int i=0;i<10li++)
System.out.println("Demo 1"+i)
try
Thread.sleep(1000);
catch(InterruptedException e)
System.out.println("some distrubance " +e);
class Demo2 extends Thread
public void run()
for(int i=0;i<10;i++)
System.out.println("Demo 2"+i);
try
Thread.sleep(1000);
catch(InterruptedException e)
System.out.println("some disturbance");
public class MultipleRuns
public void main(String args[])
Demo1 d1=new Demo1();
Demo2 d2=new Demo2();
d1.start();
d2.start();
</code>
the error its giveing is while compiling
[root@server java]# javac MultipleRuns.java
MultipleRuns.java:4: '{' expected
class Demo1.java extends Thread
^
MultipleRuns.java:58: '}' expected
^
MultipleRuns.java:55: cannot resolve symbol
symbol : method start ()
location: class Demo1
d1.start();
^
3 errors
so please guide me where iam going wrong
with regards
rama kanth

i have changed like the following even though i get the errors
<code>
import java.util.*;
import java.lang.*;
class Demo1.java extends Thread
public void run()
for (int i=0;i<10li++)
System.out.println("Demo 1"+i)
try
Thread.sleep(1000);
catch(InterruptedException e)
System.out.println("some distrubance " +e);
class Demo2 extends Thread
public void run()
for(int i=0;i<10;i++)
System.out.println("Demo 2"+i);
try
Thread.sleep(1000);
catch(InterruptedException e)
System.out.println("some disturbance");
public class MultipleRuns
public void main(String args[])
Demo1 d1=new Demo1();
Demo2 d2=new Demo2();
d1.start();
d2.start();
</code>
eroors are
[root@server java]# javac MultipleRuns.java
MultipleRuns.java:4: '{' expected
class Demo1.java extends Thread
^
MultipleRuns.java:58: '}' expected
^
MultipleRuns.java:55: cannot resolve symbol
symbol : method start ()
location: class Demo1
d1.start();
^
3 errors
so please guide me
with regards

Similar Messages

  • App running 3000 threads - Problems

    Hello everyone,
    I am writting an app that created 3000 thread, this app polls information from different sources and each thread is configured to execute a specific job.
    The app seems to create the 3000 threads without problems, and it seems to execute well for a random period of time, but afterwards the threads stops working and I don't get any exception message.
    I'm currently working on creating some logs, to gather more information about the problem, but I sincerly think that the threads are stopping in which case the logs will not help much.
    Is there any conciderations when working wiht a large amount of threads. Is there any link to documentation related to this issue ?
    Thanks very much for your help and time.
    Regands,
    Fabian.

    If the mapping between Java threads and operating-system threads is one to one (as done in several JVM implementations, like Sun's JVMs in Windows and Solaris), you can expect problems if your operating system can't handle so many threads in a single process.
    If you want to use lots and lots of threads only for breaking a single computing problem, for instance, you can try the FJTask (from the util.concurrent library from Doug Lea - http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html).
    You can use some kind of "thread pooling" (use the util.concurrent library from Doug Lea, see link above) if your problem can be handled with "thread pools".
    Some problems can be handled with the java.nio package if you want to use Asynchronous I/O - beware, it is not easy to transform a program using Synchronous I/O to a program using Asynchronous I/O.

  • Run in thread

    say a code like.....
    public static void main(String[] args) {
        for(int i = 0; i < 5; i++)
          new SimpleThread().start();
        System.out.println("All Threads Started");
    each of these threads run() method does calculation and insert DATA to DB ....do we need any synchonisation here ?Actually i fear for data corruption if multiple run method starts entering data into DB .
    can any suggest here better code or safe side[b] if needed at all
    or do i just put SQL query for insertion into DB in my run method ?
    plz comment

    not cleari meant ur that question was not clear.A transaction has a specific meaning in DBs. If multiple threads could possibly affect the same data, then you need to use transactions (and/or Java's syncing) to ensure they don't, or at least get a proper exception when they do.
    run()
    some_class sc=new some_class(Argument);
    String xml=sc.getResult(); // here i have an external
    process
    //parse XML here.
    // send XML data to DB by an SQL query
    }Problem :
    do u think there is any chance of data corruption if
    i create lots of multiple threads ?Again, not enough detail. What data do those threads share, and how do they share it?
    Have you been through the multithreading tutorial? If not, you should:
    http://java.sun.com/docs/books/tutorial/essential/threads/

  • Need to spawn multiple Automator app threads

    I have an AppleScript that runs on a folder action when files are dropped in.
    Each item triggers the same Automator app that FTPs the file.
    Problem arises when the files come in faster than the Automator app finishes each FTP job, so some are skipped. If i could have the AppleScript somehow spawn multiple Automator app threads, this would be solved.
    How would you go about solving it (sorry, can't slow down the incoming files)?
      Mac OS X (10.4.7)  

    anyone?

  • 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

  • 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 runs on a single graph

    Hi, 
     Just a quick question. I am using a Voltage Source meter that spits out an 2 arrays of data after it has done its measurement. I then plot the arrays with respect to each other using an Express XY graph. I have put the code in a for loop so that it does multiple measurements or multiple runs. So if a single run gives me a plot that looks like a straight line, 5 runs would give me 5 straight lines. My problem is that the graph, connects the last value of the previous run to the first value of the next run. I want it to plot each run independently but overlapping them in the same graph so that I can look for deviations. The XY graph is inside the for loop, so I would imagine, that when the instrument spits our the next set of data, it would be plotted in the same graph independently. 
    Any Suggestions?
    Solved!
    Go to Solution.

    Ah, I never saw the number 10 anywhere.
    You don't need to process the NaN with mathscript. It is sufficient to add the NaN to the data going to the graph terminal. Even if mathscript gets an NaN, you can probably test how it is handled.
    What does the mathscript node actually do? If it is just doing some scaling, it probably will not matter, but if it would do e.g. a linear regression, it would probably give unexpected results.
    LabVIEW Champion . Do more with less code and in less time .

  • How do I run a thread without its panel.

    I have created a vi in my application that I run as a thread. I run the thread by using an invoke node.
    When I am testing under LabView everything is fine but when I create the executable I have found problems.
    As I am starting the thread with an invoke node, the vi does not show in the application builder unless I add it as a top level vi. When I add it as a top level vi, the panel is shown when I run the application.
    I don't want to show the panel because firstly theres nothing on it anyway and secondly it looks untidy.
    Dave.

    Brian
    I tried that already with no effect. I have attached an example of my problem. This shows a meter on the front panel. A vi running as a thread writes a value to a global every 20ms and this is then read by the front panel and written to the meter.
    Dave.
    Attachments:
    Thread_test.zip ‏18 KB

  • 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.

  • Thread problem in swings

    I have made an application in swings i have stored the class files in a system and call that class files by a batfile shortcut in two diff. pcs .and i am tring to get an value of a Jtextarea in an event When I tried to run this application at the same time from 2 diff PCS,with diff string input in text area It is giving me the same vlaue.
    Tell me Y it is so.and how can i rectify it
    javauser

    Very strange... what makes you think that this is a threading problem?

  • Thread problems - shutting down.

    Okay, I've got my multi-threaded server program working just fine and all is well...until I shut down the server.
    By some quirky twist of fate, java chat servers seem to be a popular education assignment in the last two weeks, which will probably put some people off answering this simply because of all the clueless posts on the subject recently. :)
    Anyway, a little background on how I'm doing things first.
    At the top there is the Server object, which is implementing Runnable. This instances the ClientManager, creates the ServerSocket and then kicks off its own thread and loops in the run() method waiting for connections while a boolean is true. If it gets a connection it calls the ClientManager addConnection() method and passes it the received client socket.
    The ClientManager holds a List of ClientConnections and provides methods to add and remove ClientConnections. The ClientManager also runs in its own thread by implementing the Runnable interface and uses its run() method to loop through checking for incoming messages from each client.
    A ClientConnection object also runs in its own thread via the Runnable interface. This checks for incoming messages from the client and stores the String ready to be received by the ClientManager and broadcast to all ClientConnections.
    So, you've got the Server running in its own thread, the ClientManager running in its own thread and the ClientManager maintaining a List of ClientConnections, each running in its own thread.
    I'm starting my threads like this:-
    // Constructor.
    Public SomeObject() {
        start();
    // Runnable method.
    Public void start() {
        // threadObject is private class variable.
        bThreadActive = true;
        this.threadObject = new Thread(this);
        threadObject.setDaemon(true);
        threadObject.start();
    }I'm running my threadded object like this: -
    Public void run() {
        do {
            // Do work here.
        } while(bThreadActive);
        // Activates the shutdown method for this object.
        shutdownObject();
    }I'm shutting down my threads like this: -
    Public void shutdown() {
        this.bThreadActive = false;
    // The main shutdown code.
    Public void shutdownObject() {
        // Kill thread object.
        this.threadObject = null;
        // Do other stuff.
    }Which I think should work fine. Anything wrong with the above?
    I'm getting problems with NullPointerExceptions with the Server object at the point where it tries to shutdown the ClientManager. This works by shutting down all ClientConnections in the List first and then emptying the List before killing its own thread. Also, the Server object seems to shutdown before the ClientManager. And other such weirdness.
    I know you're all going to ask for specific code and a stacktrace, which I'll provide....I just want to check that my method for using threads as above is correct first, so I can rule that out - mostly because I suspect I'm missing some vital piece of knowledge on using threads....things are not working as I expect.
    Anyway, a quick answer on the above and then I'll start posting more specific info.
    Thanks all :)

    Ooops....my mistake. I was calling shutdown() twice. Once from the GUI code and automatically from after the loop in the run() method. Funny how the stacktrace doesn't drill down any further than the method that makes this call.
    Okay, its almost all working perfectly, except for this part....
        //  Start accepting client connections from the server service.
        public void run() {
             while(bThreadActive) {
                 if (sockServer != null) {
                     if (!sockServer.isClosed()) {
                         try {
                             sockClient = sockServer.accept();
                             if (sockClient != null) {
                                 this.clientManager.addClientConnection(sockClient);
                                 this.pOutput.printOutput("Connection accepted from: " + sockClient.getInetAddress().getHostAddress());
                         } catch (IOException ioe) {
                             if (bThreadActive) {
                                 this.pOutput.printOutput("ERROR: Could not accept incoming client connection");
                         } catch (NullPointerException npe) {
                             // Leave this for now.
             shutdown();
        // Shutdown the server service and disconnect all client connections.
        public void shutdown() {
            try {
                clientManager.stopThread();
                sockServer.close();
                threadServer = null;
            } catch (NullPointerException npe) {
                npe.printStackTrace();
            } catch (IOException ioe) {
                pOutput.printOutput("ERROR: Could not cleanly shutdown the server socket");
            pOutput.printOutput("Server service shut down successfully");
        // Stop the server thread (automatically shuts down).
        public synchronized void stopThread() {
            bThreadActive = false;
        }When I call the above like this from the GUI object...
        // Stop the server.
        private void stopServer() {
             try {
                  server.stopThread();
                  setGUIMode(MODE_DISCONNECTED);
             } catch (NullPointerException npe) {
                  npe.printStackTrace();
        }...the string "Server service shut down successfully" from the completion of the shutdown() method never appears, so it looks as though its not executing.
    But if I do this instead in the stopServer() method and remove the shutdown() call in the run() method, it works......but I get two (sometimes three) outputs of "Server service shut down successfully" which makes me think its being run twice somehow.....once before the ClientManager has been shutdown and once after or twice after.
    Server service shut down successfully
    Shutting down Client Manager...
    All client connections disconnected
    Client Manager successfully shutdown
    Server service shut down successfully
    Server service shut down successfully
    Any ideas?

  • Running a Thread in Oracle

    I have a java stored procedure that has a Thread in it. The Thread is bog standard (extends Thread) and all is does is sleep for 20 seconds:
                MyThread myThread = new MyThread();
                first.start(); 
                first.sleep(20000);
                first.finished = true;                    Obviously setting the 'finished' boolean to true breaks out of the run method.
    The problem is that when i run this on my desktop it sleeps for 20 seconds then exits. When I load this class into Oracle it never seems to wake up!
    Am I missing something here? Can you run new Threads in a Java Stored Procedure?
    thanks
    m

    >
    Can you run new Threads
    in a Java Stored Procedure?Probably.
    Sounds like a really bad idea to me though.

  • Re-running a Thread

    Hi all,
    I have a problem with re-running a Thread. I try to reun a Thread via its start()-method. The first time everything works fine. The second time (after the Thread finishes his first execution) the run()-method is never invoked when calling start(). Is this a bug or is there no way to re-use a Thread. Do I have to construct a new Thread instead of re-using the old one?
    Thanks for any hint, Mathias

    You can only call start() once. When the thread exits its run method, then this thread is stopped and you cannot run it again.
    Take a look at the SwingWorker example on how to reuse a thread. It works something like this:
    public void run() {
      while (running) {
        // wait until a new task is received
        // run the task
    public void newTask(Runnable task) {
      // notify the thread about this new task
    public void stopThread() {
      running = false;
      // notify the thread in case it is sleeping
    }

  • Urgent!!!!!!!HANDLER THREAD PROBLEM

    file name GetName.html
    <html>
    <body>
    <FORM METHOD = POST ACTION = "SaveName.jsp">
    what is your name?
    <INPUT TYPE = TEXT NAME=username SIZE= 20>
    <p><INPUT TYPE= SUBMIT>
    </FORM>
    </BODY>
    </HTML>
    file name SaveName.jsp
    <%
    String name = request.getParameter( "username" );
    session.setAttribute( "theName", name );
    %>
    <HTML>
    <BODY>
    Continue
    </BODY>
    </HTML>
    file name NextPage.jsp
    <html>
    <body>
    Hello, <%=session.getAttribute("theName") %>
    </body>
    </html>
    when I try to execute , SaveName.jsp is generating the following error message. what is the problem? I am using jswdk. please help. I have included tools.jar in classpath. what could be the problem?
    Unhandled error! You might want to consider having an error page to report such
    errors more gracefully
    com.sun.jsp.JspException: Compilation failed:Note: sun.tools.javac.Main has been
    deprecated.
    work\%3A8080%2Fexamples\SaveName_jsp_1.java:71: Method setAttribute(java.lang.St
    ring, java.lang.String) not found in interface javax.servlet.http.HttpSession.
    session.setAttribute( "theName", name );
    ^
    1 error, 1 warning
    at com.sun.jsp.compiler.Main.compile(Main.java:347)
    at com.sun.jsp.runtime.JspLoader.loadJSP(JspLoader.java:135)
    at com.sun.jsp.runtime.JspServlet$JspServletWrapper.loadIfNecessary(JspS
    ervlet.java:77)
    at com.sun.jsp.runtime.JspServlet$JspServletWrapper.service(JspServlet.j
    ava:87)
    at com.sun.jsp.runtime.JspServlet.serviceJspFile(JspServlet.java:218)
    at com.sun.jsp.runtime.JspServlet.service(JspServlet.java:294)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:840)
    at com.sun.web.core.ServletWrapper.handleRequest(ServletWrapper.java:155
    at com.sun.web.core.Context.handleRequest(Context.java:414)
    at com.sun.web.server.ConnectionHandler.run(ConnectionHandler.java:139)
    HANDLER THREAD PROBLEM: java.net.SocketException: Socket is closed
    java.net.SocketException: Socket is closed
    at java.net.Socket.getInputStream(Socket.java:643)
    at com.sun.web.server.ConnectionHandler.run(ConnectionHandler.java:161)

    Are you using JSWDK 1.0.1? If you are, then the implementation uses the Servlet Spec. 2.1. The set/getAttribute methods were added in 2.2.
    Try using the now-deprecated method putValue like this in SaveName.jsp.
    <%
    String name = request.getParameter( "username" );
    session.putValue( "theName", name );
    %>

  • How to 'STOP' a running java thread in J2ME?

    Dear All,
    How to 'STOP' a running java thread in J2ME?
    In the middleware viewpoint, for some reasons we have to stopped/destroyed the running threads (we have no information how these applications designed).
    But in J2ME, Thread.destroy() is not implemented. Are there other approaches to solve this problem?
    Thanks in advance!
    Jason

    Hi jason,
    Actually there are no methods like stop() and interrupt() to stop the threads in J2ME which is present in normally J2SE Environment.
    But the interrupt method is introduced in Version 1.1 of the CLDC.
    So, we can handle the thread in two ways.
    a) If it is of single thread, then we can use a boolean variable in the run method to hadle it. so when the particular boolean value is changed , it will come out of the thread.
    for eg:
    public class exampleThread implements Runnable
    public boolean exit = false;
    public void run()
    while(!exit)
    #perform task(coding whatever u needed)
    public void exit()
    exit = true;
    b) If it is of many threads then we can handle using the instance of the current thread using currentThread() method
    for eg:
    public class exampleThread implements Runnable
    public Thread latest = null;
    public Thread restart()
    latest = new Thread(this);
    latest.start();
    public void run()
    Thread thisThread = Thread.currentThread();
    while( latest == thisThread )
    #perform some tasks(coding part);
    public voi d stopAll()
    latest = null;
    while ( latest == thisThread )
    performOperation1();
    if( latest != thisThread )
    break;
    performOperation2();
    Regards,
    Prathesh Santh.

Maybe you are looking for