How organaize out in MT programms?

Hello, I started to learn some multi-threaded programms and Atomic variables. But a question about the simple example.
public class Main {
    
    /** Creates a new instance of Main */
    public Main() {
    }

    public static void main(String[] args) {
        new TestThread("T1");
        new TestThread("T2");
        new TestThread("T3");
        new TestThread("T4");
        new TestThread("T5");
        new TestThread("T6");
        new TestThread("T7");
        new TestThread("T8");
        new TestThread("T9");  
        new TestThread("T10");
        new TestThread("T12");
        new TestThread("T13");
        new TestThread("T14");
        new TestThread("T15");
        new TestThread("T16");       
        new TestThread("T17");
        new TestThread("T18");
        new TestThread("T19");
        new TestThread("T20");
        new TestThread("T21");
        new TestThread("T22");


    }
    
}

public class TestThread implements Runnable{
    
    private Thread t;
    
    /** Creates a new instance of TestThread */
    public TestThread(String name) {
        t = new Thread(this, name);
        System.out.println("Thread " + t.getName() + ": is created.");
        t.start();
    }
    
    public void run() {
        ProgGenerator pg = ProgGenerator.getInstance();
        for (int i = 0; i < 2; i ++) {
            int k = pg.next();
            synchronized (System.class) {
                System.out.println("Thread " + t.getName() + ": " + k);
            }

        }
    } 
}

public class ProgGenerator {
    
    private static ProgGenerator instance = new ProgGenerator();
    private AtomicInteger currentInt;
    
    /** Creates a new instance of ProgGenerator */
    private ProgGenerator() {
        currentInt = new AtomicInteger(1);
    }
    
    public static ProgGenerator getInstance() {
        return instance;
    }
    
    public int next() {
        int result;
        do{
            result = currentInt.get();
        }while(!currentInt.compareAndSet(result, result + 2));
        return result + 2;
    }
}
When I run it I have something like this:
Thread T1: is created.
Thread T2: is created.
Thread T3: is created.
Thread T4: is created.
Thread T5: is created.
Thread T6: is created.
Thread T7: is created.
Thread T8: is created.
Thread T9: is created.
Thread T10: is created.
Thread T12: is created.
Thread T13: is created.
Thread T14: is created.
Thread T15: is created.
Thread T16: is created.
Thread T17: is created.
Thread T18: is created.
Thread T19: is created.
Thread T20: is created.
Thread T21: is created.
Thread T22: is created.
Thread T1: 3
Thread T1: 43
Thread T2: 5
Thread T2: 45
Thread T21: 41
Thread T21: 47
Thread T20: 39
Thread T20: 49
Thread T19: 37
Thread T19: 51
Thread T18: 35
Thread T18: 53
Thread T17: 33
Thread T17: 55
Thread T16: 31
Thread T16: 57
Thread T15: 29
Thread T15: 59
Thread T14: 27
Thread T14: 61
Thread T13: 25
Thread T13: 63
Thread T12: 23
Thread T12: 65
Thread T10: 21
Thread T10: 67
Thread T9: 19
Thread T9: 69
Thread T8: 17
Thread T8: 71
Thread T7: 15
Thread T7: 73
Thread T6: 13
Thread T6: 75
Thread T5: 11
Thread T5: 77
Thread T4: 9
Thread T4: 79
Thread T3: 7
Thread T3: 81
Thread T22: 83
Thread T22: 85
So, as you can see he is not out in order of numbering of the threads (thread number 22 is near the number 3 of the thread, but it's ok). And of course it is there no error, but I cann't find reseans why the values in this son are mixed? I try to explain what I mean. We get this:
Thread T1: 3
Thread T1: 43
Thread T2: 5
Thread T2: 45
Thread T21: 41
Thread T21: 47
But not for example:
Thread T1: 3
Thread T1: 5
Thread T2: 7
Thread T2: 9
Thread T21: 11
Thread T21: 13
I can only afford, this thread can be stopped between updating the value and display it. This thread 1 first time set 3 and exit it, but then all variable son increased thread 41 but not make the exit, then walk again enter the loop value 43 and exit at the same time. If so, it's something strange that about 20 threads display nothing until the thread 1 output.
Is there a mistake? Or just everything is ok? And this code works correctly in multi-threaded program if we speak out (I mean that the update of currentInt is safe when you work with threads and each of them get good value when access)?

Published by: sphinks 16 January 2011 13:45

Published by: sphinks 16 January 2011 13:55

Hi Sphinks,

If you have needs on order of execution of the code running in java different Threads, you must take care through the synchronization of this order yourself. Without making an attempt to describe what is happening inside your computer while your program is running, the output is to be expected and your description of the reason lies in a sort of handwaving.

I like to think, however, that you can write an example program slightly less complicated which shows the AtomicInteger to work in a multi thread environment. How about having your Runnables does not print but store the values and have your main thread loop on them after they are all made to print "results"?

Thank you p.s. use [code] - labels in the future.

Tags: Java

Similar Questions

  • How find out who made changes to a virtual computer model?

    Greetings!

    We do turn several ESXi 5 boxes under vCenter Server 5 and have several directors. A few days ago one of the admins made a change to a virtual computer model and we want to know how find out who.

    Thank you!

    Have you checked the tab tasks & events of the model?

  • BlackBerry Smartphones can how put out us an emergency call when the phone is locked

    We had new mature 2 days we were... my husband has his in his pocket while he was playing pool.  The door opened and 2 cops came and asked who had that phone number. It turns out that the phone can dial 911 when if locked sound moved around.  The cops were very kind to this topic and said they get about 4 calls a week like that of blackberries.  Someone later told us there is a way to disable it. I looked through the section "help" and can not find a thing... can someone tell me how to proceed? Thank you!!

    You can place the devices in Standby Mode After locking. This will prevent the accidental keys in your pocket.

  • How zoom out / in while using the lasso tool?

    In CS4, I used to be able to zoom / zoom in cropping out something with the lasso tool. But in CS5, it doesn't let me do. How to enable that?

    Read this post-the ones by charles Badlands.

    http://forums.Adobe.com/message/2907071#2907071

    MTSTUNER

  • Satellite A200-10Z: how find out if my DVD burner compatible Labelflash

    Hello

    I have Toshiba Satellite A200-10Z provided with supermulti DVD writer device HL-DT-ST DVDRAM GSA-T20N, I don't know what manufacturer, this model!
    Does anyone know if this model compatible Labelflash? :|

    Autour Googling, I found the info that this disc must be of Hitachi. Unfortunately I didn't find out about Labelflash.

  • How to use the resistor Programmable 2720

    Hello

    I'm using and programming with the PXI-2720. Could I put the value of the resistance to the CVI program?

    I put the niswitch.fp in my project.

    I do check all relays for making 30 ohms (example value) in my program?

    Could you help me if you have code samples or references?

    I used '272 x screws of reference' for LabView.

    I'm looking for a similar instrument to the ICB driver.

    Thank you

    Insuk

    I think I get the way how to calculate.

    Thank you!

  • BlackBerry BBM stickers cat Q10 - how opt-out? Get rid of this message?

    Hello

    I'm a blackberry user because I do not play games or do eat very well.  I want a functional machine.

    How can I get rid of this offer "Send stickers" that appears after you have configured my Q10?  There is also a malware?

    By clicking on exit does not prevent the offer again to come.

    Forcing "anime"or any software for that matter, about users is not acceptable.  I need to turn it off.

    Help, please!

    Hit the right exit leaves the BBM. Hitting continue will take you right to BBM. Stickers is just a new feature in BBM BlackBerry wants you to know. You don't have to use them and you won't get anything boring. When you click on the smilies button when in a chat, there will be an icon to go to stickers if you want.

  • Stendalone DMP 4400 G how fill out the username and password

    Hi all

    I would ask that someone knows (and possible) to enter user name and password for the Web site who ask him when the page loads.

    In two words how to fill guest login form.

    Thank you!

    Hi Hristo,

    It should be possible if your page is basic authentication by the definition of the URL in the following form on the DMP:

    http://: @.

    Kind regards

    Nicolas

  • How put out ingests sequence?

    HI, I did ingest clips with time hostel cord burn but when I want to export my movie rough cut with clips ingest I can't find a way

    When I chose to put media he spent in original and no rear clamp timecord Rhinoplasty inn but at present always in offline mode and I want out put with ingest sequence clips... is there a checkbox or a setting I'm missing?

    Thank you

    If I understand you correctly, you want to export the sequence using the proxy instead of the material material full original resolution, is that correct?

    If, therefore, in the project Panel, select the source of all clips and, once selected, make right click on one of the selected clips and in the dropdown choose offline. Choose the option that keeps the source files on the disc.

    After that, the clips in the project Panel (and your sequence) only link to proxy files.

    Click anywhere in the sequence and go to the file menu > export > Media...

    you will get a dialog box warning that matter full original resolution is offline:

    Click OK, and then do your export.

    When you want to reconnect the source of full resolution for the components of the package for final output, select all the clips yet, right click on any of the selected clips and choose the Proxy > reconnect full resolution Media and reconnect the clips.

    MtD

  • How null out an article based on a column of data before posting?

    I use Apex 3.2

    I have a question that is based on the database column. My client wants me 'white out', the question which it is displayed so that the user will have to enter a new value instead of the one that is in the database.

    I tried to use a calculation "before the zone" to the element the value NULL. I can see the value prepares in debugging after extraction of the line took place, but when the item is displayed, it contains the value of the database, not my calculated valuie.

    I also tried using a field of text unsourced and then doing a submit after calculation to set the value of the element in a column of data from there, but no luck that way either.

    Also tried emptying the cache memory point, but I think it happens much too early.

    There must be a simple way to do...

    Any suggestion?

    No problem user486652 (name?).

    Yes, the $s function is one of the ApEx of built-in them - to see the ApEx documentation under the API, the Javascript API reference and you will find a variety of built-in functions that make all sorts of things. For Javascript, in general, take a look at www.w3schools.com for some really good reference material and tutorial - I use it constantly.

    OK, if you want to set the browser field to empty once the page loaded. Since it is an event of the page, it is not something that fires for a form field element, if you do not want the code here. ApEx 3.2, change the attributes of the page, and you will see a setting called "Attribute of HTML Body". You'll see a helpful note ball below the setting: this is the place to add onload events. The appropriate syntax will be:

    onload="$s('P2_REMEDY_TICKET', '');"
    

    Once the ApEx puts everything together and the rendering of the page, copy the following code will tell the browser to perform this $s function after the page load.

    But be aware - if you take a look at aid for that setting, you will see that it mentions that this will only work if your page template includes the #ONLOAD substitution string #. Do not know if all pages provided by ApEx models have already #ONLOAD #, but every one I've used. If your code still does not work, check your page tempate. In the area of definition, under header, you should see a body with something like tag:

    ...
    ...
    ...
    

    If it is, your page template supports the HTML Body attribute. If your body tag does not have a #ONLOAD #, add it.

    Hope this helps,
    John

    If you find this information useful, please indicate the 'useful' or 'correct' post so that others benefit. *

  • How spool out put of several scripts and get a single spool output file

    Hello

    I have a master script that calls three other scripts. The three scripts produce their own files of spooling. But I would like to have the master script also produce a single output (in addition to the release of three individual, I mean). How to do this? Can you please help.
    Following are the scripts:
    --m.sql (master script)
    spool c:\m.log
    @1.sql
    @2.sql
    @3.sql
    spool off
    
    --1.sql
    spool c:\1.log
    insert into test values(1);
    commit;
    spool off
    --2.sql
    spool c:\2.log
    insert into test values(2);
    commit;
    spool off
    
    spool c:\3.log
    insert into test values(3);
    commit;
    spool off
    
    --table used
    SQL> desc test
     Name                                      Null?    Type
     ----------------------------------------- -------- ----------------------------
     A                                                  NUMBER
    When I run the above script m.sql it does not produce the other 3 log files (1.log, 2.log etc.), but m.log (which is master log file which should have output of each of the three call script) is an empty file with 0 bytes!

    Thank you

    Published by: orausern on May 1st, 2011 03:17

    Try this:

    sqlplus uid/pwd  @m.sql >AllSpools.log
    

    PS: Add a statement of 'exit' at the end of the main script.

    : p

  • How analog out simultaneously a signal and its negation?

    Hello

    I use the 6024E and trying to send a signal with an analog output.

    However, at the same time, I would like to send a negation of this the other analog output signal.

    It seemed simple until I realized that this timed task alone is supported at a time.

    Any suggestions would be most appreciated... I have attached the vi I thought that (but now realize will never) work.

    Thank you!

    You should be able to put the two channels in the same spot.  Not had time to test this, but it should work.

  • How to out high-level digital signal (5V from 1V) on usb-6210?

    Hi, I work with a OR usb-6210 and so I did not all channels of analog output that I can use. I hope that I can use the digital output for my application because I am creating a switch I can synchronize my editing. I need 5V output for my device run and currently, I am only able to get 1V.

    -Teo

    Outputs digital are dip lent TTL of the stent, since, your load is attractive more current that can provide the device and drop the voltage. Please provide information on what you are connected to or look at the other posts where users have had exactly the same problem. You probably just a conductor connected to the digital output.

  • How to Flash an ARM Cortex M3 with a compiled hex file?

    I need to update the flash on an ARM Cortex M3 using the hex file compiled through a JTAG port. I do PCB test fixtures and need to update the firmware, if not later.  I use TestStand and Labview on Windows XP PXI system. I have a DAQ 6289 but you can add modules more if I need to. What would be the best way to do this?

    You work with the LabVIEW Embedded for ARM Module and trying to deploy a hex file created there? Or is this a file separate hex that you want to deploy your surfboard while testing with LabVIEW and TestStand? If you just need to deploy a hex file, you would use a program like rousselinemamiaritiana to push the code to the Board of Directors. This thread speaks of the peaks with external programs called LabVIEW programming methods:

    http://forums.NI.com/T5/LabVIEW/how-can-I-control-PIC-programmer-with-LabVIEW/TD-p/138120?requireLog...

    It is a different material, but probably the same idea, you can use: call an executable that loads the file hex on the Board. You have the program used to push the current software to the Board of Directors?

    Kind regards

  • How can I remove disc stuck in player on IQ846

    I have a disc stuck in the player bluray on my IQ846, how come out or remove the drive?

    Hello

    Follow the steps in the link below to remove the optical drive, you will see the "pin hole" to mechanically release the drive.

    http://support.HP.com/us-en/document/c01557650

    Kind regards

    DP - K

Maybe you are looking for

  • Change the color of the counter

    We have an application that would be really the meter or the caliber, I hope we could change the color. I've searched the forums and while it's a little change of color of eacharea, there is nothing on [i] Add [/ i] areas or change the [i] [/ i] area

  • Get videos from camera to Windows Movie Maker

    I am new Windows Mov Mkr and my Sony camera. I downloaded videos from 'My Photos' file using the "PMB" program provided with the camera.  However, in trying to get these videos to edit them in WMM, I get the error message "too many methods to fire th

  • 7510 printer photosmart HP all in one

    Impossible to update the printing software via internet due to no internet connection for printer displays on the screen of the printer when you try to upgrade. printers that all apps find internet and I can't print wireless and e print from all my c

  • I can ' t find my graphics driver HP 15-n034SO

    Hi, I recently bought a HP 15-n034SO and replaced to original HDD with a ssd and installed windows 7. I am now almost finished downloading all the drivers separately, but I still miss the integrated graphic card which is supposed to be: drivers of AM

  • Windows 10 Bios error

    Hello Today, when I opened my computer I came across a message and he said is not supported by windows 10 free upgrade so I continued and he opened and said to check for compatibility and says BIOS, how do I fix. Thank you peace and blessings, Gman