Difference in how to start a thread

What is the difference between these two thread implementations?
Thread t = new Thread(new Runnable() {
   public void run() {
      // do work here
t.start();And this...
Thread t = new Thread(){
   public void run() {
      // do work here
t.start();

What is the difference between these two thread implementations?Not much, in a practical sense. In one case you're implementing Runnable; in the other, you're extending Thread. Here's my usual discourse on the matter:
Prefer implementing Runnable to extending Thread. Think of Threads as the workers and Runnables as the job itself. You implement Runnable because your "unit of work" or whatever you want to call it IS-A Runnable -- that is, something that will do its job start-to-finish when you call run. You would only extend Thread if your class IS-A Thread -- that is, it has a reason to do everything Thread does, and you need to slightly add to or modify Thread's behavior.

Similar Messages

  • How to start a thread properly?

    I have a problem on how to start a thread properly. I have a test case.
    public class Main
    static String db;
    public static void main ( String[] args ) {
    new Main() ;
    public Main () {
    runStopDB () ;
    private void runStopDB () {
    String db = "dbBase" ;
    ClientUpdate clientUpdate = new ClientUpdate ( db ) ;
    public class ClientUpdate extends Thread
    boolean nonStop = true ;
    String dbName;
    public void getSession ( ){
    System.out.println ( " dbName = " + dbName+ " in getSession()" );
    public void setStop () {
    nonStop = false ;
    public void run () {}{
    int i = 0 ;
    while ( nonStop ) {
    System.out.println ( " In while " + i );
    i++;
    System.out.println ( " run() finished !" );
    public ClientUpdate ( String dbName ) {
    System.out.println ( " dbName = " + dbName +"in constructor()" );
    this.dbName = dbName ;
    System.out.println ( " this.dbName = " + this.dbName +"in constructor()" );
    ==============================
    The thread of clientUpdate starts immediately when �ClientUpdate clientUpdate = new ClientUpdate ( db )�. The constructor of clientUpdate event did not be executed. My questions are
    1. Why does the thread execute automatically before start() being called in this case?
    2. How do I modify the code which the thread will start after start() being called? I can initialize the fields for the constructor.
    Thanks,
    Sean

    Modify below code.
    public void run () {}{===>
    public void run () {
    "{}" is not needed.

  • How to start a thread after the execution/termination of another thread.???

    Hello,
    How to start a thread after the execution/termination of another thread....???
    For example:
    consider two threads: ThreadA and ThreadB
    I could start the ThreadB after the execution of ThreadA.
    How to identify the termination of one thread.....???
    Please help me...
    Thanks & Regards,
    Kayalvizhi

    What do you mean with "it doesn't work"? Do you get a compiler error? Do you get an exception at runtime? What's the error message?
    Jesper

  • How to start two threads at the same time

    Hi there,
      I want to include multithreading in the CVI program. I have two tasks which has no dependence between them, so I would like to start two threads for perform the tasks. I follow the introduction http://www.ni.com/white-paper/3663/en/ to start my code. In my code, I add a command button, when it is pressed, I create two threads to perform the tasks. In each task, I have a big loop and in each iteration, I use ProcessSystemEvents to avoid no response on system message. But it doesn't work actually, the program suspended. I wonder must I initialize the threads in main. I am looking for a way to start the threads in the callback function for a button since I am not starting those threads at the beginning but while it is triggered.
    the main frame of the code looks
    int CVICALLBACK Test1(void *functionData)
    { int i=0;
    for (i = 0; i<100000; i++) {ProcessSystemEvents();}
    return 0;
    int CVICALLBACK Test2(void *functionData)
    int i = 0;
    for (i = 0; i<100000; i++) {ProcessSystemEvents();}
    return 0;
    int CVICALLBACK cmdcb(int panel, int control, int event, void *callbackData, int eventData1, int eventData2)
    { int threadID1, threadID2;
    if (event==EVENT_COMMIT)
    SetPanelAttribute(panelHandle, ATTR_DIMMED, 1);
    CmtScheduleThreadPoolFunction(DEFAULT_THREAD_POOL_HANDLE, Test1, NULL, &threadID1);
    CmtScheduleThreadPoolFunction(DEFAULT_THREAD_POOL_HANDLE, Test2, NULL, &threadID2);
    CmtWaitForThreadPoolFunctionCompletion (DEFAULT_THREAD_POOL_HANDLE, threadID1, 0);
    CmtWaitForThreadPoolFunctionCompletion (DEFAULT_THREAD_POOL_HANDLE, threadID2, 0);
    return 0;
    Attachments:
    TestThread.zip ‏239 KB

    In my opinion your threads may be simply lasting longer than expected due to an incorrect sleep policy of threads paired with with ProcessSystemEvents () in the loop.
    I made up a quick example that shows this behaviour: playing with "Do not sleep" and "Call ProcessSystemEvents" options you can see how threads execute.
    BTW: do not forget to release the thread function IDs at the end of functions.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?
    Attachments:
    thread.zip ‏7 KB

  • How to start two threads at a time

    hi to all,
    can any one tell me how we can start two or more threads at a time
    this is my req in the application i want to check that
    can any body help me in this regard.
    ashok

    If you are starting a whole bunch of threads, and want them to be eligable for execution at about the same time (i.e. dont get staggered due to the overhead of starting), then you can use locking / waiting.
    I've not really had / wanted to do this before, but I suppose something like the following might work:
    import EDU.oswego.cs.dl.util.concurrent.Latch;
    import EDU.oswego.cs.dl.util.concurrent.Sync;
    public class StartupTest {
      private void test() {
        Latch startGun = new Latch();
        // create and start some threads - I'll just create one
        Thread t = new Thread(new TestRunnable(startGun));
        t.start();
        // all started? Ok - fire the start gun to release them
        startGun.release();
      private class TestRunnable implements Runnable {
        private Sync startGun;
        TestRunnable(Sync startGun) {
          this.startGun = startGun;
        public void run() {
          waitForStart();
          // what ever you were going to do here......
        private void waitForStart() {
          try {
            startGun.acquire();
          } catch (InterruptedException e) {
            // what ever... I'll just bharf.
            throw new RuntimeException(e);
    }Even with this, your threads aren't going to actually start working all at exactly the same time - but they'll all be eligable to start working at the same time.

  • How to start/ restart the service in visual admin of SAP WAS 6.4?

    I have installed the sneak preview version of SAP NetWeaver WAS 6.4 for default Database MaxDB. While developing a simple application to manage simple database table citymaster with 2 columns in jsp I am getting error as
    Exception e com.sap.engine.services.jndi.persistent.exceptions.NameNotFoundException: Path to object does not exist at : java.comp.
    Looking at visual admin tool for WAS 6.4 all the entries are in color blue but the last entry for 'DATASOURCE' is in RED color where 'java.comp/env/JDBC/DATASOURCE' is the jndi reference created for default DataSource.
    Can any one help me that why the last entry is in RED and it that say that some error has occured or that entry is not started then how to start that?
    Please help....

    Dear Daniel,
    I have checked the Visual Administrator's  JNDI Registry service entry in the ejbContexts node but there is no entry for the project which I have created.
    It get deployed while I right click on the project's ear file and click on "Deploy on J2EE Engine". But same as before while checking in Browserthe site gives the same error...
    503   Service Unavailable
    Application cannot be started!
    Details: com.sap.engine.services.deploy.exceptions.ServerDeploymentException: Application bcone.com/EntityCMPAppln cannot be started, because it has hard reference to resource CONFIG_DB with type javax.sql.DataSource, but it is not active on the server.
         at com.sap.engine.services.deploy.server.ReferenceResolver.processUsageOfComponent(ReferenceResolver.java:508)
         at com.sap.engine.services.deploy.server.ReferenceResolver.beforeStartingApplication(ReferenceResolver.java:337)
         at com.sap.engine.services.deploy.server.application.StartTransaction.begin(StartTransaction.java:149)
         at com.sap.engine.services.deploy.server.application.StartTransaction.beginLocal(StartTransaction.java:285)
         at com.sap.engine.services.deploy.server.application.ApplicationTransaction.makeAllPhasesLocal(ApplicationTransaction.java:355)
         at com.sap.engine.services.deploy.server.application.ParallelAdapter.runInTheSameThread(ParallelAdapter.java:120)
         at com.sap.engine.services.deploy.server.application.ParallelAdapter.makeAllPhasesLocalAndWait(ParallelAdapter.java:224)
         at com.sap.engine.services.deploy.server.DeployServiceImpl.startApplicationLocalAndWait(DeployServiceImpl.java:4170)
         at com.sap.engine.services.deploy.server.DeployServiceImpl.startApplicationsInitially(DeployServiceImpl.java:2390)
         at com.sap.engine.services.deploy.server.DeployServiceImpl.clusterElementReady(DeployServiceImpl.java:2267)
         at com.sap.engine.services.deploy.server.ClusterServicesAdapter.containerStarted(ClusterServicesAdapter.java:41)
         at com.sap.engine.core.service630.container.ContainerEventListenerWrapper.processEvent(ContainerEventListenerWrapper.java:101)
         at com.sap.engine.core.service630.container.AdminContainerEventListenerWrapper.processEvent(AdminContainerEventListenerWrapper.java:19)
         at com.sap.engine.core.service630.container.ContainerEventListenerWrapper.run(ContainerEventListenerWrapper.java:80)
         at com.sap.engine.core.thread.impl4.SingleThread.execute(SingleThread.java:70)
         at com.sap.engine.core.thread.impl4.SingleThread.run(SingleThread.java:111)
    Please help me, how to recover this error.
    Rgds,
    Vivek

  • How to start a application with a login window?

    hi there
    does anyone have any idea on how to start an application with a login window? a login window is the first frame or window to be displayed when an application starts running. and only correct login id and password have been entered the real application will start. any sample out there? thank you.

    You can start a new thread by making a thread object and passing it an implementation of a runnable object. Runnable has just one method, public void run(), this is was gets executed in a second thread. perhaps the code you would use would look something like this.
    <code>
    // set up thread for login window
    new Thread(new Runnable() {
    public void run() {
    // construct your login window here
    // when you are done processing the
    // password....
    if(goodPassword) {
    authorized = true; // a global variable
    notifyAll(); // don't forget this
    else {
    System.exit(42);
    }).start();
    // control does not stop this code gets executed while
    // the above thread is running.
    // Set up main program here. This is done in the
    // backround.
    while(!authorized) {
    synchronized(this)
    { wait(50); }
    // now when the user logs in this frame pops
    // up real quick.
    myFrame.setVisible(true);
    </code>
    Hope you can figure it out.. good luck :)

  • How to let new thread to access EJB

    I start new thread in Servlet class and I want this thread to call EJB business method but I get following error:
    javax.naming.NameNotFoundException: Name comp/env/ejb not found in context "java:"
    Probablly because thread has no credentials and so on. I know this concept violates J2EE specs but I don't know how to make timer to call business mathod every N minutes (I use J2EE 1.3 so I can't use Tiemr EJB).
    I suspect that this new thread has no credentials and no role. What happens if I set run-as some role in servlet? As I saw new thread still has no credentials and role.
    Can anyone suggest me how can I set credentials to new thread so it can call EJB business method or how to implement timer service in J2EE 1.3.

    I start new thread in Servlet class and I want this
    thread to call EJB business method but I get
    following error:
    javax.naming.NameNotFoundException: Name comp/env/ejb
    not found in context "java:"It may happen because you'r new thread doesnt have information (JNDI environment) about EJB references.
    Can anyone suggest me how can I set credentials to
    new thread I guess it's server specific.
    so it can call EJB business method or how
    to implement timer service in J2EE 1.3.Don't use EJB reference. Lookup EJB by it's global JNDI name.

  • How to stop the thread?

    Hi,
    How to stop the thread in java. This is my program.
    import java.net.InetAddress;
    public class ThreadPing extends Thread {
         ThreadPing(String pingIP)
              super(pingIP);
              start();
         public void run()
              try
              String pingIP = Thread.currentThread().getName();
              InetAddress inet = InetAddress.getByName(pingIP);
              Boolean get=inet.isReachable(1500);          
              if(get==true)
                   System.out.println(inet.getHostName());               
              }catch(Exception e)
         public static void main(String args[])
              for(int i=1;i<=100;i++)
                   String pingIP = "192.168.1."+i;
                   ThreadPing tp = new ThreadPing(pingIP);
    Thanks in advance.

    The simplest way to stop all the thread is to make all thread daemons and exit the program when you want them to stop.

  • How to get each thread in the threadpool

    Hi,everyone.I'm now learning java.util.concurrent package and I have two questions about the threadpool.
    1) How to get each thread in the threadpool;
    2) How to get each thread's data in the threadpool and dispaly them onto GUI;
    e.g :
    There are 5 threads in the threadpool(ThreadPoolExecutor) and I have 100 tasks(Runnable or Callable),every task scans a directory(every task scans a different directory),how can I display the "real-time" count of the files in the directory which the current 5 threads in the threadpool scan onto the ListView Items in the GUI?

    Willings wrote:
    Hi,everyone.I'm now learning java.util.concurrent package and I have two questions about the threadpool.
    1) How to get each thread in the threadpool;You don't
    2) How to get each thread's data in the threadpool and dispaly them onto GUI;
    e.g : You don't
    There are 5 threads in the threadpool(ThreadPoolExecutor) and I have 100 tasks(Runnable or Callable),every task scans a directory(every task scans a different directory),how can I display the "real-time" count of the files in the directory which the current 5 threads in the threadpool scan onto the ListView Items in the GUI?You should notify your "monitor" when you add something to the pool, and the Runnable/Callable should notify the same "monitor" when it starts to execute, and during its processing. Finally you notify the monitor when the execution has completed.
    Kaj

  • How to start with AOL

    Hi,
    Can anyone please provide me the documents on how to start and learn with Oracle apps AOL(technical).
    Please provide me the required documents to learn.
    Thanks in advance.

    Duplicate thread.
    How to start with AOL
    How to start with AOL

  • How to make a Thread loop?

    Hi, I was wondering how to make a thread start over again from the beginning once it finishes, if it hasn't been stopped already.

    package src.Utility;
    public class ThreaTest extends Thread{
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              ThreaTest threaTest= new ThreaTest();
              while(true){
                   try{
                   if (!threaTest.isAlive()){
                        threaTest= new ThreaTest();
                        threaTest.start();
                   }//else{
                        //System.out.println("");
                   }catch (Exception e) {
                        e.printStackTrace();
         public void run(){
              System.out.println("-----11---------");
    }try the above code and then tell me if this loop works for you???

  • Here's my Vent of the Day - How about one topic/thread per subject?

    I see lots of topics/threads started that are exactly the same as ones already out there, and many of those could be answered if the OP would just search what's already been said, or read generally available information before posting. And then there are so many posts for which even the OP knows don't have an answer. It's just hard to wade through all these repetitive posts to find the ones that need answers or could be informative to all.
    _For instance, how about a single thread for some of these_?
    How do we get our free cases
    When will Apple make a hardware change to iP4
    Do you think I should buy now or wait
    I'm happy with my phone, why aren't you
    Let's all complain about Apple, Steve, whatever
    Now what was it that was said in the Press Release? (like maybe go read it)
    Face Proximity should be fixed
    Antenna Problem should be fixed
    So that's my vent for the day (everyone else is doing it). Come to think of it, I'm gonna change the topic of this post to "Here's my Vent of the Day"
    Message was edited by: DianeX
    Message was edited by: DianeX

    R C-R wrote:
    Keep in mind that a lot of new or occasional Discussions users are not familiar with how the Discussions search engine works & that it is, to be kind about it, more than a little quirky. For instance, even many regular users don't know that the default search box scope is different depending on the category you use it from. And compared to "smart" search engine technology like say Google or bing uses, you often need to use the arcane, 1990's era syntax mentioned in Search Tips to get good results.
    Plus, users not already familiar with an issue or its terminology often have no idea how to create a good search query that doesn't produce an overwhelming number of unrelated hits.
    Besides, venting & ranting are close cousins & the ToU make it clear these forms of self-indulgence are not really acceptable topics for Discussions to begin with. I'm sure a huge number of Discussions users are frustrated by all the topics taken over by such things, but {ahem} venting that frustration is just adding more fuel to the fire, so to speak.
    My point may have been more clear if I hadn't somehow posted this on the Discussions area instead of the iPhone4 one, where there are continual repeats of the same topics (most of which have no answer anyway)

  • How to start or shut down database using sql developer in windows

    Dear Sir/Madam,
    how we start or shut down database using sql developer in windows
    we are using oracle 11g release2, unix, java & oracle oracle weblogic administration
    Thanks & Regards
    Manish Kumar
    Datbase Team
    TCS Ltd.

    HI, Welcome to OTN form,
    SHUTDOWN is not a SQL statement but a SQL*Plus command . You cannot use SHUTDOWN in PL/SQL.
    Check following link:
    http://docs.oracle.com/cd/E11882_01/server.112/e16604/ch_twelve042.htm#i2699551
    More Information please check OTN discussion: https://forums.oracle.com/thread/2349159
    Thank you

  • How to Start and Stop Processes?

    How to Start and Stop Processes?
    Im trying to create a program which allows me to Start and Stop (and Restart) GameServers. I will then expand on this so i can start and stop them through a web applet with build in useraccounts.
    Currently the way we do this is to log into the server using a RemoteAssistance. Which is not very safe as the users have the abbility to do anything on the server and potentially corrupt it.
    Below is my code for how i start the servers. But i dont know how i would stop the process.
                    private void startServers()
                   for(GameServer gs : servers)
                        int ID = Integer.parseInt(gs.getID());
                        if(isChecked(ID))
                             try
                                  String cmd[] = gs.getStartString();
                                  Runtime.getRuntime().exec(cmd);
                                  int sleepPeriod = Integer.parseInt(sleepField.getText());
                                  Thread.sleep(sleepPeriod*100);     
                             catch(Exception e)
                             System.out.println(e);
                   }//end of iterator
                   JOptionPane.showMessageDialog(null,"All Selected Servers Have been started.","Servers Started",2);     
         }//end of startserversAnyhelp would be great thanks.

    Using the process class would give you a nicer API, but using destroy isn't a nice way to shutdown a process. Its like killing the process with your task manager. You should make a connection in some way with the game server and tell it to shutdown in stead (gracefull termination).

Maybe you are looking for