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.

Similar Messages

  • 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 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 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 run two threads simultaneously ....?

    Hello All,
    I Am developing an application which send some data to server and from remote place that data is fetched and displayed.
    For this i am using Java Servlet as a server which accepts data by readObject() method of object output stream and writes using writeObject() method.
    At remote end i am fetching the data and printing that using thread.Data is fetched using URL's method
    URL urlServlet = new URL("URL of servlet");
    URLConnection con = urlServlet.openConnection();But while fetching it takes some time say 1-2sec because of that my display is not continuous.
    I want to write an application such that two threads will be running(in synchronization),second thread will start after few ms of 1st thread.One thread will continuously fetches data and other will display, so that there will be no delay at all while displaying of data.
    How to do this?
    Thanks In Advance.

    Google on: java producer consumer example
    Kaj

  • How to sync two threads ?

    Hi!
    I've two threads in my app running at the same time. One of them shows some pics in a slideshow, the other plays some background music. How can I sync one of the threads to stop when the other ends ?
    thanks in advance

    I would recomend use listening.methodology: one class is a listener, and the other calls that listening method, which sets some variable which the first thread ckecks regurarily.
    Eg:
    interface StopListener{ public void stop();}
    class A implements StopListener{
    boolean stopped=false;
    public void stop(){stopped=true;}
    public void doSome(){
    while(!stopped){
    //do whatever
    Gil

  • How to run a thread for second time ?

    I have a written a ThreadPool, but I found that basically a thread is not running for the second time. i.e First i call run() method and call stop(). If i call again run() method for the same thread, it is not running. What should I do, If i want to run the thread for the second time ?
    class NewThread implements Runnable {
    String name;
    NewThread(String a) {
    name=a;
    public void run() {
    try{
    for(int i=0;i<5;i++) {
    System.out.println("Thread :" + name + " #" +i);
    Thread.sleep(5);
    catch (Exception e) {
    e.printStackTrace();
    class threadRunnableTest {
    public static void main (String args[]) {
    Runnable runnable=new NewThread("BaSkAr");
    Thread thread = new Thread(runnable);
    try{
    System.out.println("First Thread is starting !!!");
    thread.start();
    Thread.sleep(2000);
    System.out.println("First Thread it to be stopped!!");
    thread.stop();
    System.out.println("Second Thread is starting !!!");
    thread.start();
    Thread.sleep(2000);
    System.out.println("Second Thread it to be stopped!!");
    thread.stop();
    catch (Exception e) {
    e.printStackTrace();

    baskark wrote:
    I have a written a ThreadPool, but I found that basically a thread is not running for the second time. i.e First i call run() method and call stop(). If i call again run() method for the same thread, it is not running. What should I do, If i want to run the thread for the second time ?
    class NewThread implements Runnable {
    String name;
    NewThread(String a) {
    name=a;
    public void run() {
    try{
    for(int i=0;i<5;i++) {
    System.out.println("Thread :" + name + " #" +i);
    Thread.sleep(5);
    catch (Exception e) {
    e.printStackTrace();
    class threadRunnableTest {
    public static void main (String args[]) {
    Runnable runnable=new NewThread("BaSkAr");
    Thread thread = new Thread(runnable);
    try{
    System.out.println("First Thread is starting !!!");
    thread.start();
    Thread.sleep(2000);
    System.out.println("First Thread it to be stopped!!");
    thread.stop();
    System.out.println("Second Thread is starting !!!");
    thread.start();
    Thread.sleep(2000);
    System.out.println("Second Thread it to be stopped!!");
    thread.stop();
    catch (Exception e) {
    e.printStackTrace();
    It's usually helpful to check the documentation:
    [http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#start()|http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#start()]
    start
    public void start()Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
    The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
    It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
    So, make a new java.lang.Thread

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

  • How to start two instances of InDesign server independently?

    Hello,
    we have a multi instance InDesign server installation.
    And we are able to start two instances of InDesign server on different ports.
    But now we would like to use different plugins for different instances.
    Is it possible somehow? For example install InDesign server two times in different folders or something like that?
    Thank you in advance.

    InDesign plugin loading can be controlled via a file "PluginConfig.txt", refer to search for details.
    InDesign Server has separate configuration folders per instance/configuration.
    *If* the search path for the PluginConfig.txt falls into this folder, that would be the easiest approach.
    I don't have a server installation with me to try it out.
    Dirk

  • How to run two thread parallel y on two cores of dual-core ??

    I want to run two threads on two cores ???
    is there any package which support parallel computing??
    can we do this by using java.util.concurrency pakage??
    Thanks you
    please Reply.....

    vikram_p wrote:
    I want to run two threads on two cores ???ok
    Threads are automatically spread over the available cores, as the OS sees fit.
    is there any package which support parallel computing??Java does so without any external libraries.
    can we do this by using java.util.concurrency pakage??yes
    One question mark per question is plenty, thank you.

  • How to avoid two threads creating the same entity?

    I seem to have a problem with a race-condition. Two threads are trying to
              create the same entity. One thread calls a finder with no success and
              creates the entity, meanwhile - before the entity gets persisted
              (ejbStore()) - the other thread also calls a finder with no success,
              creating the
              same entity.
              My transaction isolation level in the weblogic-ejb-jar.xml is
              <transaction-isolation>
              <isolation-level>TRANSACTION_READ_UNCOMMITTED</isolation-level>
              <method>
              <ejb-name>ejb</ejb-name>
              <method-name>*</method-name>
              </method>
              </transaction-isolation>
              I've also tried <isolation-level>TRANSACTION_SERIALIZABLE</isolation-level>
              with no significant change in behavior.
              In the ejb-jar.xml
              <container-transaction>
              <method>
              <ejb-name>ejb</ejb-name>
              <method-name>*</method-name>
              </method>
              <trans-attribute>Required</trans-attribute>
              </container-transaction>
              

              Try setting delay-updates-until-end-of-tx to false for your bean. Try experimenting
              with concurrency-strategy of Exclusive. Or re-write your code to not check for
              existence before creation; just create the bean and let the db return a duplicate
              key exception.
              simon.
              "Daniel" <[email protected]> wrote:
              >I seem to have a problem with a race-condition. Two threads are trying
              >to
              >create the same entity. One thread calls a finder with no success and
              >creates the entity, meanwhile - before the entity gets persisted
              >(ejbStore()) - the other thread also calls a finder with no success,
              >creating the
              >same entity.
              >
              >My transaction isolation level in the weblogic-ejb-jar.xml is
              ><transaction-isolation>
              ><isolation-level>TRANSACTION_READ_UNCOMMITTED</isolation-level>
              ><method>
              ><ejb-name>ejb</ejb-name>
              ><method-name>*</method-name>
              ></method>
              ></transaction-isolation>
              >
              >I've also tried <isolation-level>TRANSACTION_SERIALIZABLE</isolation-level>
              >with no significant change in behavior.
              >
              >In the ejb-jar.xml
              ><container-transaction>
              ><method>
              ><ejb-name>ejb</ejb-name>
              ><method-name>*</method-name>
              ></method>
              ><trans-attribute>Required</trans-attribute>
              ></container-transaction>
              >
              >
              

  • How to start two or more tasks at the same time?

    Hi all,
      I have few tasks setup to send analog and digital output to different channel with buffer and given sampling rate. I need to precisely control the timing of samples output to each channel. But if I start the task in labwindows
        DAQmxStartTask(taskHandle1)
        DAQmxStartTask(taskHandle2)
        DAQmxStartTask(taskHandle3)
    they actually not start at the same time since they are exectued in sequence. I wonder how much time delay will be if I start each task in sequence. Also, is it possible to have 2 or more tasks started at the same time?
    p.s. I think it will be easier if I could bind different channels to a single virtual channel but I don't think it is possible to create a signle virtual channel with analog channel and digitial channel.

    RobertoBozzolo wrote:
    I had success in doing something similar on the input side by sharing the same sample clock across the tasks with:
    DAQmxCfgSampClkTiming (DigitalTaskHandle, "/Dev1/ai/SampleClock", 1000, DAQmx_Val_Rising, DAQmx_Val_FiniteSamps, 1000);
    In my application I had the power to have the same acquisition speed on all tasks, so that the sample clock could be same on all of them.
    The conceptual framework is this one (pay attention to the step order):
    Setup your AO task
    Setup your DO task
    Set the DO task to share the AO sample clock with the instruction given above
    Start the DO task (IMPORTANT: it must precede the AO task start, so that DO task is started but does not generate samples)
    Start the AO task
    If you have different sample speed on the tasks, I suppose an alternative is to use a start trigger sharing some digital signal among them. I have seen examples that use a separate counter output as a start trigger.
    Thanks a lot. It gives me a good information, I think that will help. I am encountering another sitution, if task1 is analog output with continuous samples with rate 100000 samples/second and task2 and task3 are a single digital sample (i.e. write only 1 sample to one digital line). In task1, I write continuous samples and there will be a spike (of 2.2V) at the time 1.2ms after the task started. And I want to write to the digital channels (task2 and task3) at 0.2ms before the spike was set in task1. In this case, there is only one sample written to DO task, so how does it work to use the sample clock source?
    In your last suggestion, we could use tirgger but how does it help? Is there any example I can follow? Thanks.

  • How to start OC4J at Linux boot time

    Hello,
    I am using Linux AS 3.0 and i have installed OC4J ( 9.0.4) ok, and OC4J also work fine.But each time i want to start OC4J , i must execute command java -jar oc4j.jar at console.
    Now, I want to start OC4J automatic at System startup ( ie: Linux boot time ).How can i do?
    Thanks.

    Just put your OC4J start/stop commands in a rc script.
    Scripts in the directories
    /etc/rc.d/rc2.d
    /etc/rc.d/rc3.d
    /etc/rc.d/rc5.d
    will be called by the operating system with the command line option start.
    The number in the directory names represent the desired run level of the machine.
    Scripts in the directory
    /etc/rc.d/rc0.d
    will be called during shutdown with the command line option stop.

  • How to Link two Facts with Different Time Granularity (Year, Quarter) to a Single Time Dimension

    Hello All,
    I have the below scenario where i have Two Facts Fact Quarterly and Fact Yearly but one Time Dimension which has Quarter grain.
    So my question is how do i Establish relationship from Fact Yearly to Time Dimension??
    Ex: 

    Hi naveej,
    According to your description, you want to know how to build the relationship with time dimension and fact tables. Right?
    Based on your screenshot, it's better to have only one fact table for sales and build the relationship with time dimension. To determine quarterly or yearly data only depends on how you slice the time dimension. However, I notice that the Revenue for year
    is different from the aggregated Profit for quarters. If the Revenue and Profit are different measure, you need to have two fact tables. And you should build the relationship (Regular) between TimeDim and FactYearly on YYYY attribute.
    Reference:
    Defining a Fact Relationship
    Best Regards,
    Simon Hou
    TechNet Community Support

  • How to display two pages at a time in smartform

    Hi folks,
    I have requirement that i need to display  two pages for each record of the output table . the page 1 is not simillar to page 2 . page1 contains few templates and page2 contains other templates not simillar to first one.
    my case, it displays only the first page eventhough i tried using command line.
    Is there any exact step to followed  to over come this problem.
    Please suggest the solution.
    Thanks ,
    Hemum.

    hi,
    can u please tell me how and where u are looping throuhg the internal table
    check that.
    regards,
    Ravi Valluri

Maybe you are looking for

  • Safari unexpectedly quits a few seconds after launching iHeartRadio

    I have a user that is having an issue with Safari quitting after launching iHeartRadio.  I know, a user should not be allowed to stream content at a work place, but I am curious on how to fix the issue.  It was working in 10.6.8.  I updated her yeste

  • CD Burn Error 4450 - solved!

    I kept getting the dreaded 'unknown error 4450' when burning from iTunes to CDs. Once I changed the burn speed to '12x', it worked fine! I wich I knew that before I wasted a stach of blank CD's I hope this helps some of you!

  • Files .NEF of Nikon D800: how  can CS6 read them?

    Files .NEF of Nikon D800: how  can CS6 read them?

  • Subreport header on more than one page ?

    <p>Hi all,</p><p> </p><p>I need to create some reports with big subreport inside !</p><p> </p><p><font color="#000099">Main report </font></p><p><font color="#000099">subreport1  (10 pages and 9 columns)</font></p><p><font color="#000099">subreport2

  • SunONE Portal integration with webseal , Tivoli and Oblix

    Hi , Can anyone pls explain me the integartion details of SunONEPS 6 with Tivoli , Oblix and Webseal. I basically would like to know how handshakeing happens between all these. regards Arun