How to use Thread

Hi,
I am trying to write a program that does a background process. The process is controlled by two buttons: Start and Stop. I thought I'd use threads, but it does not work; the start button remains depressed and the user cannot click on the Stop button. The line calling run() is executed and execution transfers to the run method in my Thread subclass, which is wrapped in an infinite loop. The line after the run() method is never reached. It is as if it is not creating an extra thread at all.
I have written something basic which is similar, the same problem occurs with this code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CounterFrame extends JFrame {
    private JPanel pnButtons;
    private JButton btStart;
    private JButton btStop; 
    private ThreadTester threadtester;
    public CounterFrame() {
        pnButtons = new JPanel();
        btStart = new JButton("Start");
        btStop = new JButton("Stop");
        btStart.addActionListener(new StartListener());
        btStop.addActionListener(new StopListener());   
        pnButtons.add(btStart);
        pnButtons.add(btStop);
        add(pnButtons);
        pack();
        threadtester = new ThreadTester();
    private class StartListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            threadtester.run();
    private class StopListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                threadtester.sleep(Long.MAX_VALUE);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
    private class ThreadTester extends Thread {
        int counter;
        public ThreadTester() {
            counter = 0;
        public void run() {
            while(true) {
                System.out.println(counter);
                counter++;
                try {
                    sleep(1000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                yield();
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CounterFrame().setVisible(true);
}Can anyone advise where I am going wrong, please?

Please run, don't walk to the article on the Sun site (you can search for it) entitled Concurrency and Swing (or something similar). Problems I see include:
1) Don't call run on a thread as that will just "run" the run method and not create a background thread. Instead you call "start".
2) Don't call Thread.sleep() on the EDT or the Event Dispatch Thread. This is the single thread that Swing uses to draw components and to interact with the user. Calling Thread.sleep on it will put your whole program to sleep which is not what you want.
3) Consider using a Swing Worker, or better still a Swing Timer.
Again, read the article and you will understand this better.

Similar Messages

  • How to use threads in JSP???

    hello
    i want to use threads with JSP.
    i want to write a jsp page which will
    start 2 different threads. the 1st thread should just display a message and the second page should redirect this page to another jsp page.
    till the redirection is goin on, the message should be displayed in the browser from the 1st thread.
    i dont know actually how to use threads in JSP by implementing the Runnable insterface, if not m then how do i do it ??
    thanx
    Kamal Jai

    Why do you want to use threads to do this ??
    If you write a message and do a redirection, the message will be displayed until the other page will be loaded into the browser...
    I already launched a thread from a JSP but it was for a four hour process where the user can close his browser windows.

  • How to use thread only for progress bar.....

    Hello,
    I am working on an application which is taking time to load. Now I want to use a progress bar to tell the user of the application that It is taking time to load. How to do it... I read the Java swing tutorial and went through the example. Please tell me what to do. Because I am unfamiliar with Threads and I am not using thread anywhere in my application.

    You are using threads. All Java execution occurs on threads. Write a Java GUI and you're in a multithreaded environment - there's no way out of that.
    If your "application is a complex one" then you would be better advised to understand threads than to try and pretend that they don't exist. For a start, if you don't think you're using threads then you're destined to run in to all sorts of problems as regards an unresponsive GUI, as you're probably now finding out.

  • How to use threads to reconnect a socket to a server in TCP/IP

    I want to know how to reconnect a socket to a server in TCP.
    Actually i wanted to do reconnection whenever a SocketException for broken connection etc. is thrown in my code. This I want to do for a prespecified number of times for reconnection in case of broken connection.When this number decrements to zero the program will exit printing some error message. I was planning to use threads by way of having some Exception Listeners but i am not sure How?
    Any suggestions will be really helpful..
    please help.
    Edited by: danish.ahmed.lnmiit on Jan 28, 2008 2:44 AM

    I want to know how to reconnect a socket to a server in TCP.There is no reconnect operation in TCP. You have to create a new Socket.

  • How to use Threads in Java?

    Hi all,
    I want to run many programs in the same time. So i want to know if anybody can help me using threads in java. Any help or code will be very appreciated!
    Thanks in advance,
    A. Santos

    All you have to do is create classes that extend Thread, implement their run() methods and then instantiate and call their start() methods:
    public class Class1 extends Thread {
      public void run() {
        // do what you need to do
    public class Class2 extends Thread {
      public void run() {
        // do what you need to do
    public class Class3 extends Thread {
      public void run() {
        // do what you need to do
    public class Main {
      public static void main (String [] args) {
        Class1 c1 = new Class1();
        Class2 c2 = new Class2();
        Class3 c3 = new Class3();
        c1.start();
        c2.start();
        c3.start();
    }

  • How to use Threads

    I have a number of objects which extend Thread, and I want to set them all running, and then 'wait' for them all to finish, before doing something else.
    The pseudocode for what I want to do is given below:
    while threads not finished {
    wait();
    Finshed!
    I was adding them all to a ThreadGroup and waiting until ThreadGroup.activeCount() == 0, but the spec of my code says I can't use the Thread constructor which takes the group as a parameter.
    Therefore, my problem is this: how to I implement the above pseudocode so I use wait()?
    Thanks!

    If you strictly have to use wait(), seems like you will need to change your thread class implementations as you need to some object, which is synchronized and shared between all the threads. I dont think its going to be a good solution for you.
    In case you want to avoid all that, using join all the threads would help, code piece for this is:
    public class ThreadsJoin {
        public static void main(String[] args) {
            MyThread[] threads = new MyThread[10];
            for (int x = 0; x < threads.length; x++) {
                try {
              threads[x] = new MyThread();
              threads[x].start();
                }catch(Exception e) {
                    e.printStackTrace();
            for (int x = 0; x < threads.length; x++) {
                try {
              threads[x].join();
              System.out.println("Thread "+ x +" finished");
                }catch(Exception e) {
                    e.printStackTrace();
            System.out.println("All threads finished... so in main");
    class MyThread extends Thread {
            public void run() {
                try {
                Thread.sleep(100);
                }catch(Exception e) {
                    e.printStackTrace();
                System.out.println("thread executed");
    }There are methods where you poll in for the active threads using isAlive() or getActiveCount(), but this is a better way to do the task. In fact join() is nothing but wait() for a thread to finish. You can even specify timeout for this waiting period.
    regds,
    CA

  • How to use thread to monitor a file

    Hi
    I have a situation where i want to monitor a file while current java process is running, for example
    The process would be like below,i have to do it using Java 1.4
    1 Start Main Java Class
    2 Start Another thread to monitor a file, from this main Java Class
    3 Return control back to main java class to do future processing
    4 When the process in this class is done, kill the monitor process.
    5 If the file is modified by external process, do some processing in the thread,
    What i did was as below, the main java class
    Thread t = new Thread(new TestOptimizationThreadWorker());
    t.run();
    // continue doing the process
    t.stop();the other thread class is as below
    public class TestOptimizationThreadWorker implements Runnable
         public void run()
              // monitor the external file here
    }But some how the control does not come back to main program after i run the thread,
    Any suggestions
    Ashish
    Edited by: kulkarni_ash on Sep 26, 2007 10:06 AM
    Edited by: kulkarni_ash on Sep 26, 2007 10:53 AM

    Hi
    Yes after changing, t.run() to t.start(), it works, but what are the issues you see,
    i have attached the whole code below
    Java Main Class
    public class TestOptimizationThread
         public TestOptimizationThread()
         public String doMessage()
              TestOptimizationThreadWorker tt =     new TestOptimizationThreadWorker();
              Thread t = new Thread(tt);
              System.out.println ("In Do message");
              try
                   System.out.println ("Before starting thread");
                   t.start();
                   System.out.println ("After starting thread");
              catch(Exception exc)
              finally
                   System.out.println ("in finally");
                   tt.changeB();
              return "";
         public static void main(String args[])
             new TestOptimizationThread().doMessage();
    }Java Thread class
    public class TestOptimizationThreadWorker implements Runnable
         private boolean b = true;
         public TestOptimizationThreadWorker()
              System.out.println ("Creating this class ");     
         public void run()
              System.out.println ("In Run Method");
              int i =0;
              while(b)
                   System.out.println ("int "+ i);     
                   i++;
         public void changeB()
              b = false;     
    }Ashish

  • How to use threads in this script???

    Hi, I�m new to java, and I my first script is a reciprocal link checker but I have a problem with the speed. I have the next class for check a html page to search for a string (the reciprocal link). The problem is that when I pass the script more than 50 pages to check, the proccess ibs very slow. I thought that the problem is stablishing the connections, because it makes only one at a time.
    I think, that with threads the I can accelerate the proccess, but I don�t know how to implement here. If you can give some advise, very thanks in advance. Here is the class:
    import java.net.URL;
    import java.net.URLConnection;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    class checkHtml {
    boolean comprobarReciproco(String thisUrl, String reciproco) {
    String toReturn = null;
    boolean res = false;
    try {
    URL url = new URL(thisUrl);
    URLConnection thisConn = url.openConnection();
    BufferedReader receiver = new BufferedReader(new InputStreamReader(thisConn.getInputStream()));
    String line = new String();
    // Leemos del buffer de entrada l�nea a l�nea
    while((line = receiver.readLine()) != null) {
    if (line.indexOf(reciproco) != -1 ){
    res = true;
    break;
    } catch(Exception e) {
    System.out.println("Error:" + e);
    return res;
    public static void main(String[] args){
    checkHtml x = new checkHtml();
    System.out.println(x.comprobarReciproco("http://www.somewebpage.com/blahblah.htm","reciprocal"));

    I make the call to this proccess in the main class, with this method:
    public String [][] comprobarRecip(String arr[][], String recip){
    checkHtml check = new checkHtml();
    int j=0;
    String enlacesfinal[][] = new String[tamanyoLinks(arr)][2];
    for (int i=0; i < tamanyoLinks(arr); i++){
    // Si no est� el reciproco nos guardamos el enlace en enlacesvalidos
    if (check.comprobarReciproco(arr[0],recip) == false){
    enlacesfinal[j][0] = arr[i][0];
    enlacesfinal[j][1] = arr[i][1];
    j++;
    return enlacesfinal;
    Is in this method, where I must use the threads? Thanks a lot!

  • How to use Thread.sleep() with Java Berkeley Base API?

    Hi,
    I have explained the weird problem about the server was too busy to response to SSH but it continued to finish to run (Server not response when inserting millions of records using Java Base API
    Even I tried to increase CachSize and renice Java program, but it did not work. So, I am thinking to set sleeping time for threads in Java Berkeley Base API (using “ps” command, there were 18 light weight processes created). My program did not implement transaction or concurrency because it simply creates (millions) databases records only. Is it possible and correct to do like this in the code:
    try{
    //do create a db record
    Thread.currentThread().sleep(1000);//sleep for 1000 ms
    catch(ItrerruptedException ie){
    Thank you for your kindly suggestion.
    Nattiya

    where can I get the help doc about use AT commands in java.
    Can you give me some code example about this. It is
    difficulty to me to write it myself.You simply have to send the characters and receive the characters via the comm extension. Here is the ITU standard command set - http://ridge.trideja.com/wireless/atcommands/v250.pdf. Various modems and other devices extend this in a number of ways, you may need to find documentation specific to your device as well. But start with the standard.

  • How to use Threading Concept in oracle

    Hi all,
    I am having requirement such that i have to execute a function after insert of data in one table.due to performance issues i have to execute this function using java pooling.if anybody having idea regarding this one please share.
    I have tried by using simple javaThreading but it is not working.
    Regards,
    Ramesh.

    public static void main (String args[] ) throws Exception {
    log("main thread is: " + Thread.currentThread());
    TaskProcessor taskProcessor[] = new TaskProcessor[5];
    Thread threads[] = new Thread[taskProcessor.length];
    for (int i=0; i<taskProcessor.length; i++) {
    taskProcessor[i] = new TaskProcessor(i);
    threads[i] = new Thread(taskProcessor);
    threads[i].start();
    for (int i=0; i<taskProcessor.length; i++) {
    if (threads[i].isAlive()) {
    threads[i].join();
    * Thread to run many concurrent connections
    private static class TaskProcessor implements Runnable {
    private int number = 0;
    public TaskProcessor(int number) {
    this.number = number;
    public void run() {
    try {
    log("Thread started: " + Thread.currentThread());
    // Get a connection
    Connection conn = ConnectionFactory.getConnection();
    // Sleep and yield so that other threads can run
    Thread.yield();
    //Thread.sleep(1000);
    Thread.yield();
    Connection conn1 =ConnectionFactory.getConnection();
    log("Thread " + Thread.currentThread() + ": First Con: " + conn);
    log("Thread " + Thread.currentThread() + ": Second Con: " + conn1);
    if (conn1 != conn)
    throw new Exception("Connections dont match: " + conn + ": " + conn1);
    log("Thread " + Thread.currentThread() + " over");
    } catch (Exception e) {
    System.out.println("Exception"+e);
    private String getLeastLoadedPool() {
    if (lastNodePoolUsed == null) {
    lastNodePoolUsed = "1";
    return "1";
    if (lastNodePoolUsed.equals("1")) {
    lastNodePoolUsed = "2";
    return "2";
    else {
    lastNodePoolUsed = "1";
    return "1";
    // in connection factory get connection factory
    public synchronized static Connection getConnection() throws Exception {
    if (singletonFactory == null)
    singletonFactory = new ConnectionFactory();
    String poolId = (String) nodePoolTracker.get();
    if (poolId == null) {
    // one and store it in the thread
    poolId = singletonFactory.getLeastLoadedPool();
    nodePoolTracker.set(poolId);
    log("No Pool Associated:" + Thread.currentThread() + ", adding: " + poolId);
    return singletonFactory.getConnection(poolId);
    else {
    log("Pool Associated:" + Thread.currentThread() + ", " + poolId);
    return singletonFactory.getConnection(poolId);
    after creating this class by using lodajava i have loaded in oracle.
    Regrads,
    Ramesh

  • How to use thread pool in glassfish

    I am using jdk 1.6 with glassfish 2.1
    in admin console i found threadpools under Configuration> Thread Pools
    my questions are
    is this thread pool is accessible to programmers (just like in websphere threadpool is accessible to programmers through work manager and asynch beans)
    can I do the same thing using glassfish (eg. WorkManager wm = new WorkManager(_threadpool_) )
    or is there any other way to do this.
    Is there any way to use the threads in the threadpool to run some batch job in parallel?
    what exactly the purpose of this threadpool in glassfish, I mean it used internally bu glassfish or programmers have to use it explicitly in there code

    It is pretty straight forward. You just create an executor instance and feed it runnable objects. For example:
    import java.util.concurrent.*;
    public class ExecutorExample {
        static class Worker implements Runnable {
            public Worker(int id) {
                this.id = id;
            public void run() {
                for(int i = 0; i < 100; i++) {
                    System.out.printf("Thread %d iteration %d of 100%n", id, i);
                    try {
                        Thread.sleep(100);
                    catch(Exception e)
            private int id;
        public static void main(String[] args) {
            BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(200);
            Executor e = new ThreadPoolExecutor(10, 10, 1, TimeUnit.SECONDS, queue);
            System.out.println("Creating workers");
            for(int i = 0; i < 20; i++)
                e.execute(new Worker(i));
            System.out.println("Done creating workers");
    }

  • Playing two midi files at once using threads?

    Hi all, I have the following simple code here which plays a midi file, but I'm not sure how to use threads to play two midi files at once:
    import org.jfugue.*;
    import javax.sound.midi.*;
    import java.io.*;
    public class MidiPlayer {
    public static void main (String [] args) {
    try {
    Player player = new Player();
    player.playMidiDirectly(new File("C:\\Sounds\\bach.mid"));
    } catch (IOException e) {
    } catch (InvalidMidiDataException e) {
    Is there a way to use a thread for this class so that in another class I can call 'start' twice and have the parameters be the midi file locations (e.g. "C:\\Sounds\\bach.mid" & "C:\\Sounds\\bach2.mid").
    Any kind of help would be great, thank you!

    Something like the below.
    import org.jfugue.*;
    import javax.sound.midi.*;
    import java.io.*;
    public class MidiPlayer {
    public static void main (String [] args) {
    String fileName = "c:\\Sounds\\bach.mid";
    Thread t1 = new Thread(new MyRunable(fileName));
    t1.start();
    String fileName2 = "c:\\Sounds\\bach2.mid";
    Thread t2 = new Thread(new MyRunable(fileName2));
    t2.start();
    } // main
    class MyRunnable implements Runnable {
    private String fileName
    public MyRunnable( String fileName) {
      this.fileName = fileName;
       public void run() {
         Player player = new Player();
        player.playMidiDirectly(new File(fileName));
    } // MyRunnable
    } //

  • Connection between server and client using thread

    hi
    i am new to java..i hav done a program to connect a server and client...but i hav not used threads in it..
    so please tel me how to use threads and connect server and client..i tried it out not getin...i am havin thread exception...my program is as shown below
    SERVER PRG:
    import java.io.*;
    import java.net.*;
    public class Server{
    String clientsen;
    String serversen;
    public void go(){
    try{
         ServerSocket serverSock=new ServerSocket(6789);
         while(true) {
         Socket sock=serverSock.accept();
         BufferedReader inFromClient=new BufferedReader(new InputStreamReader(sock.getInputStream()));
         BufferedReader inFromuser=new BufferedReader(new InputStreamReader(System.in));
         DataOutputStream outToClient=new DataOutputStream(sock.getOutputStream());
         clientsen=inFromClient.readLine();
         System.out.println("From Client: "+clientsen);
         System.out.println("Reply mess to Client");
         serversen=inFromuser.readLine();
         outToClient.writeBytes(serversen+'\n');
    } catch(IOException ex) {
         ex.printStackTrace();
    public static void main(String[] args) {
         Server s = new Server();
         s.go();
         CLIENT PRG
    import java.lang.*;
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.lang.Thread;
    import java.applet.Applet;
    class Client1
    public static void main(String argv[]) throws Exception
              String Sen;
              String modsen;
              BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in));
    Socket clientSocket=new Socket("192.168.1.2",6789);
              DataOutputStream outToServer=new DataOutputStream(clientSocket.getOutputStream());
              BufferedReader inFromServer=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
              System.out.println("Enter the mess to be sent to server");
              Sen=inFromUser.readLine();
              outToServer.writeBytes(Sen + '\n');
              modsen=inFromServer.readLine();
              System.out.println("FROM SERVER: " +modsen);
              clientSocket.close();
    please send me the solution code for my problem...

    sorry for inconvenience...
    SERVER PROGRAM
      *import java.io.*;*
    *import java.net.*;*
    *public class MyRunnable implements Runnable*
       *public void run() {*
       *go();*
    *public void go(){*
    *try {*
        *String serversen;*
       *ServerSocket  welcomeSocket=new ServerSocket(6789);*
       *while(true)*
    *Socket connectionSocket=welcomeSocket.accept();*
    *//BufferedReader inFromClient=new BufferedReader(new //InputStreamReader(connectionSocket.getInputStream()));*
    *System.out.println("enter the mess to be sent to client");*
    *BufferedReader inFromuser=new BufferedReader(new InputStreamReader(System.in));*
    *DataOutputStream outToClient=new DataOutputStream(connectionSocket.getOutputStream());*
    *//clientsen=inFromClient.readLine();*
    *//System.out.println("From Client: "+clientsen);*
    *//System.out.println("Reply mess to Client");*
    *serversen=inFromuser.readLine();*
    *outToClient.writeBytes(serversen+'\n');*
    *} catch(IOException ex) {*
    *        ex.printStackTrace();*
    *class Server1{*
    *public static void main(String argv[]) throws Exception*
         *Runnable threadJob=new MyRunnable();*
    *Thread myThread=new Thread(threadJob);*
    *myThread.start();*
    *}*CLIENT PROGRAM
    import java.io.*;
    import java.net.*;
    class Client2
    public static void main(String argv[]) throws Exception
              //String Sen;
              String modsen;
              //BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in));
    Socket clientSocket=new Socket("192.168.1.2",6789);
              //DataOutputStream outToServer=new DataOutputStream(clientSocket.getOutputStream());
              BufferedReader inFromServer=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
              //System.out.println("Enter the mess to be sent to server");
              //Sen=inFromUser.readLine();
         //     outToServer.writeBytes(Sen + '\n');
              modsen=inFromServer.readLine();
              System.out.println("FROM SERVER: " +modsen);
              clientSocket.close();
    this is the code which i hav used using thread but i am gwetin error..ts is the error
    Exception in thread "main" java.lang.NoSuchMethodError : Main

  • Using Threads to schedule tasks

    Hi There
    Does anyone know how to use threads to schedule tasks say a function to be called every 30 mins or another fn to be called every 12 hours
    Code snippets will be helpful
    Thanks
    Mum

    Make a Timer which get's up periodically the threads (every time they need to perform the task). When the threads gets up it performs it's task and the came back to sleep, remaining in this state until the timer wakes up it again.
    abraham.

  • How to use a Java Thread in a Java Stored Procedure?

    I am working with java stored Procedures but i have a problem when i use threads.While the thread is running all the processes are blocked because the thread is not detatched.I don't know if it is impossible to use Thread in a java stored procedure.i made many researches but didn't find information about this case of Thread.If someone knows what to do in this case it will be helpfull for me.Thanks

    The JAR is already load by using CREATE JAVA RESOURCE ... or "loadjava -resolve –force -user p/p@SID –genmissing -jarasresource MyJar.jar"
    If we can create a resource by SQL or loadjava, how can I use it in my java code?
    Edited by: 847873 on 28 mars 2011 06:05
    Edited by: 847873 on 28 mars 2011 06:07

Maybe you are looking for

  • Problem with boolean type in Informix via ODBC

    Hello, I'm connecting to an Informix database from an Oracle database via the ODBC Gateway. The connection works fine. However, when I select a boolean type column from a table in the Informix database, nothing is returned and I get the following err

  • User Exit for ME51N Transaction

    Hi folks,      I have a requirement regarding ME51N Tocde. If the user enters the internal order number in ME51N, while creating Purchase Requisition, the corresponding cost center should be displayed in the cost center field by default. I have found

  • How to set a global configuration for Value Interaction

    Hi there i have this problematic situation about some of my dashboards, cause i need to set the same configuration for all of them in the part of the value interaction, some of there have in the "default situation" drill and others have "navigation"

  • ALE Config

    Hi, When i am configuring the ALE in my system, i have created the logical systems, the RFC test is successful. and i have even modelled the distribution but when i try to exute the profile parameters i am getting the msg like: Log for Partner Profil

  • What is the best Collection/Iterator to use?

    Anyone come across this scenario before? I have a list of elements that I want to put into a Collection/List of some description. I then want to iterate through the list searching for an element that matches my requirements. When I find one I then wa