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();
}

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.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 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 the Public Java API

    Is it possible to use the Public Java API to write a custom transformation in Java and use this in OWB. i.e. Say I have a Dateofbirth field in my source database and an Agegroup field in the target database, and I write a transformation in Java to take the Dateofbirth as an input parameter to the method and calculate the Agegroup e.g. 25-30, and return it from this method which then populates the Agegroup field in the target database. If so, how do I go about this?

    Martin,
    In general, yes you could... but you do not need to. You could use the UI to implement this requirement. The public Java API is there for you to manipulate metadata. How you implement your system, is independent of that.
    The way you would go about the case you just mentioned... you would write the Java code, deploy it into the database, wrap it in a PL/SQL procedure or function, and call it from OWB.
    Would this be a good idea...? I think no. Unless you have very complicated calculations that can only be performed in Java, I strongly encourage you use the PL/SQL language. Reason being: transformation will be much faster, because there is no need to translate PL/SQL into Java and back again.
    Hope this helps,
    Mark.

  • I need to learn how to use all about java & mysql...help me!

    I have a situation here, I need to learn how to use java with mysql
    . Can I connect to a MYSQL DB with servlets?
    how can I build an e-mail server with java (no matter how difficult)
    please, I need help, and I really apreciate your help.
    thank you very much!!

    I have a situation here, I need to learn how to use
    java with mysql
    . Can I connect to a MYSQL DB with servlets?Yes... documentation to help you connect to any database can be found at http://java.sun.com/products/jdbc. To connect to MySQL, you'll need drivers (sourceforge.net), and the specific connection URL for those drivers will be included in the documentation.
    how can I build an e-mail server with java (no matter
    how difficult)If you're fairly new to JSP/Servlets, you may be in over your head here, since an email server is no easy application to code. Here's a link to the source code for the JAMES project... Apache's Java email server... maybe you can find some useful information there...
    http://www.ibiblio.org/pub/packages/infosystems/WWW/servers/apache/jakarta/james/source/

  • How to use connec with java 6.0 ?

    I often use the function below to connect Database:
         public Connection getConnection(){
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    conn=DriverManager.getConnection("jdbc:odbc:EmployeeManagerDB","sa","sa");
    System.out.println("Get connection successfully!");
    catch(Exception e){
                   System.out.println("Error: " +e);
    return conn;
    but now, with Java 6.0 . don't use "class.forName....for method"
    can you tell me how to use it??
    thanks !

    but now, with Java 6.0 . don't use
    "class.forName....for method" Where did you get this idea?He's perfectly correct. JDBC 4.0 takes advantage of the Java SE Service Provide mechanism in Java 6 to do away with the requirement. So, if you have Java 6 and a JDBC 4 driver (it's a mandatory feature) you simply omit the forName() call.
    The only problem is that there aren't that many complete JDBC 4 drivers out there yet.

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

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

  • HELP: do u know how to use forms pluggable java component...

    Hi all,
    I'm looking for a sample for using java component within Forms: how to installl them? how to use them? ...
    Cyryl from france

    Did you already check the demos on OTN at:
    http://otn.oracle.com/sample_code/products/forms/content.html
    Check the viewlets to see how to develop and deploy them and you can even get code to use them.

  • How to use Barcode for Java

    First of all, If this is the wrong forum to post this, please tell...
    Now to the bussines:
    Surfing through the web I found something called Barcode For Java, and my question is how to implement in java, how to use it in a program, what's the purpose of it.Also if this is compatible with EasyEclipse for Java 1.3.1
    Any help would be appreciated, thanks

    Now let me get this straight.
    -- You don't know what this is
    -- You don't know what it's for
    -- You don't know how it's used
    So WTF do you know that makes you want to use it?
    db

  • How to use xdk for java

    Hi,
    I have downloaded the xdk for java and i have unzipped them into my c:\xdk-java folder.
    I have oracle 8.1.7 database and i want to use this xdk for java to generate xml files.
    How to start with this and how to use this tool to generate xml files from my database.
    Anyone can give me the steps for using this and generating xml files.
    Any help will be appreciated..

    Hi,
    You can start from reading the XSU document and try the demos come with the package. The document is at:
    http://otn.oracle.com/docs/tech/xml/xdk_java/doc_library/Production9i/doc/java/xsu/xsu_userguide.html

  • How to use xml in java

    hi,
    can anybody tell me in what scenarios we can use xml in java,jsp and servlets.
    give some information and help on this..
    regards,
    javafan

    define scenarios. You can use XML in java at any time you want.
    - check out SAX http://java.sun.com/xml/tutorial_intro.html
    - check out Xerces 2 http://xml.apache.org/xerces2-j/

  • How to use CreateNamedPipe in Java

    Hi am integrate my java application with a c++ application & i don't have control over the c++ application, already the c++ application integrated with other c++ application using pipes, Now i want to integrate with Java. But i found that java doesn't support CreateNamedPipe().
    Can anyone tell me how to get this done? But am able open,read,write pipes in java but createNamedPipe() causes the problem.
    Thanks in Advance
    Sahe

    Hi, I created a JNI Wrapper for WinAPI CreateNamedPipe() am able to establish connection between VC++ and Java, But am struck when am trying to sending/receiving data. When am using BufferedWriter to Send data to VC++ application by that time VC++ application says Pipe Instance is buzy cannot open!! Am enclosing my code here, if anybody come across this please help me..
    import java.io.*;
    import java.util.*;
    class Win32 {
        public static native int CreateNamedPipe(
            String  pipeName,      
            int dwOpenMode,       
            int dwPipeMode,           
            int nMaxInstances,          
            int nOutBufferSize,
            int nInBufferSize,  
              int nDefaultTimeOut,  
            int[] secAttrs);       
    class OneToOne extends Thread {
         public OneToOne() {
              start();
         public void run() {
                try{
                   int size=0;
                   BufferedWriter pipeWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("\\\\.\\PIPE\\\\\\.\\pipe\\MCHPPipe_OUT")));
                  while(true) {
                        Thread.currentThread().sleep(500);
                        pipeWriter.write("CONNECT");
              catch (IOException e){
                    e.printStackTrace();
              catch (InterruptedException e){
                     e.printStackTrace();
        public static void main(String[] args) throws IOException {
              System.out.println("Creating a Named Pipe...");
              Win32.CreateNamedPipe("\\\\.\\PIPE\\\\\\.\\pipe\\MCHPPipe_IN", //"\\\\.\\pipe\\SamplePipe",
                         0x00000003, //ACCESSMODE
                         0x00000000, //PIPEMODE
                         1,       // no instance
                         1024,    // out buff size
                         1024,    // in buff size
                         0x1D4C0,//Time out
                         null);   // secuirty
                Win32.CreateNamedPipe("\\\\.\\PIPE\\\\\\.\\pipe\\MCHPPipe_OUT",
                         0x00000003, //ACCESSMODE
                         0x00000000, //PIPEMODE
                         1,       // no instance
                         1024,    // out buff size
                         1024,    // in buff size
                         0x1D4C0,//Time out
                         null);   // secuirty
              System.out.println("PIPE IS CREATED");
              new OneToOne();
        static {
              System.loadLibrary("OneToOne");
    }

  • 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

Maybe you are looking for

  • Problem with quantity field in BDC

    hi experts,                i am trying to upload  data from internal table to SAP using BDC, but while uploading quantity fields it is giving error as "Input fields is longer than screen field", Is there any method to upload quantity fields to SAP.  

  • Using an old BT Hub 4 to repeat the wireless signa...

    Hi all - Newbie alert I've been having an issue with my wireless connection for a good while and have been promised lots of times that upgrading to a newer hub would resolve them. It means I have gone from a Home Hub 3 to a 4 and now have upgraded to

  • IE margin doubling problem

    I am working on a site. I have a floated horizontal list of items at the very top of the header. It looks fine in Firefox and Safari but in IE 8 it forces the last item on to a second line. I have read about the margin doubling problem with IE and I'

  • Using Guest user for Visual Composer

    Hi everybody, Can we use "guest" or one unique portal user to show a report from VC to everyone? Thanks...

  • Routing rule clarification in receiver determination

    Hi guys, I have a routing condition which says I_ZBAPI_DL01/ZZCOMDEST = DN_XC and I_ZBAPI_DL01/ZZCOMDEST_II = DN_08 and I_ZBAPI_DL01/ZTIB_LFART ="ZRWO" and contains(I_ZBAPI_DL01/ZADI_SUBSCRIBER,"JRW") and T_ZBAPI_DL12/ZTIB_BSARK = "RBCO" In the above