Trying to learn about threads

Hi guys,
I'm trying to learn more about threads......i've written a small program for a better understand, but i don't understand the order of the output i'm getting:
public class testme {
public static void main(String[] args) {
Theshape mover = new Theshape("go");
     mover.start();
System.out.println ("checkpoint 1");
System.out.println ("checkpoint 2");
     }//main
}//class testme
class Theshape extends Thread {
public int count;
public String thego;
Theshape (String gg){
     thego= gg;
count=0;
}//constructor
public void run(){
try {
do{
System.out.println (thego);
sleep(1000);
System.out.println ("johnny");
count=count+1;
}while(count<8);
} catch (InterruptedException e) {}
}//run          
}//class theshape
........the output i get is:
checkpoint 1
checkpoint 2
go
johnny
go
johnny
go
johnny
go
johnny
go
johnny
go
johnny
go
johnny
go
johnny
I would like to know why "checkpoint 1" and "checkpoint 2" is printed first, even though the call to the run method is made before the two statements. i would have thought that the two checkpoint statements would be printed last.
Can anyone help?
Thanks,
Zaf

After you've issued the 'mover.start()' call, a new thread pops into existence. The first thread (your main thread) continues to run while the second thread prepares itself to start up. On your machine, this startup takes a (little) while, so your main thread is able to print those two line just before the other thread is able to print something. That's all there is to it. If you put a 'Thread.sleep(1234)' between those two println statements in your main thread, the output would probably be a bit different. Give it a try.
kind regards,
Jos

Similar Messages

  • I have a new iPhone 5S.  While trying to learn about it, I accidentally recorded a voice memo with no content.  I cannot now figure out how to get rid of it.  There is a banner across the top of my phone with this memo which I don't want.  Help!

    I have a new iPhone 5S.  While trying to learn about it, I accidentally recorded a voice memo with no content.  I cannot now figure out how to get rid of it.  There is a banner across the top of my phone with this memo which I don't want.  I have deleted it from iTunes but cannot get it off the phone.  Help!

    The banner usually indicates that the memo is "Paused." If you go back into voice memos, touch the word "Done" beside the big red pause button, give it a name, then it will show in a list. Touch the memo in the list then touch the trash can icon that should appear.

  • Question while Learning about Thread

    I am learning about thread.
    I ran the sample producer/consumer programe in Java Thread Tutorial in which I added two lines of printing out codes in class CubbyHole to observe the runing sequence better.
    The result made me a bit confused. I imagine that the result "Producer #1 put: 1" should be printed out right after "put 1", why it appeared after "get 1" and "Consumer #1 got: 1"?
    Codes are listed below:
    public class ProducerConsumerTest {
    public static void main(String[] args) {
    CubbyHole c = new CubbyHole();
    Producer p1 = new Producer(c, 1);
    Consumer c1 = new Consumer(c, 1);
    p1.start();
    c1.start();
    public class Producer extends Thread {
    private CubbyHole cubbyhole;
    private int number;
    public Producer(CubbyHole c, int number) {
    cubbyhole = c;
    this.number = number;
    public void run() {
    for (int i = 0; i < 10; i++) {
    cubbyhole.put(i);
    System.out.println("Producer #" + this.number
    + " put: " + i);
    try {
    sleep((int)(Math.random() * 100));
    } catch (InterruptedException e) { }
    public class Consumer extends Thread {
    private CubbyHole cubbyhole;
    private int number;
    public Consumer(CubbyHole c, int number) {
    cubbyhole = c;
    this.number = number;
    public void run() {
    int value = 0;
    for (int i = 0; i < 10; i++) {
    value = cubbyhole.get();
    System.out.println("Consumer #" + this.number
    + " got: " + value);
    public class CubbyHole {
    private int contents;
    private boolean available = false;
    public synchronized int get() {
    while (available == false) {
    try {
    wait();
    } catch (InterruptedException e) { }
    available = false;
    System.out.println("get " + contents);
    notifyAll();
    return contents;
    public synchronized void put(int value) {
    while (available == true) {
    try {
    wait();
    } catch (InterruptedException e) { }
    contents = value;
    System.out.println("put " + contents);
    available = true;
    notifyAll();
    The result is as below:
    put 0
    Producer #1 put: 0
    get 0
    Consumer #1 got: 0
    put 1
    get 1
    Consumer #1 got: 1
    Producer #1 put: 1
    put 2
    get 2
    Consumer #1 got: 2
    Producer #1 put: 2
    put 3
    get 3
    Consumer #1 got: 3
    Producer #1 put: 3
    put 4
    get 4
    Consumer #1 got: 4
    Producer #1 put: 4
    put 5
    get 5
    Consumer #1 got: 5
    Producer #1 put: 5
    put 6
    get 6
    Consumer #1 got: 6
    Producer #1 put: 6
    put 7
    get 7
    Consumer #1 got: 7
    Producer #1 put: 7
    put 8
    get 8
    Consumer #1 got: 8
    Producer #1 put: 8
    put 9
    Producer #1 put: 9
    get 9
    Consumer #1 got: 9

    Hi alaska,
    The reason you got those results are because these are
    threads. The execution of the order of thread is
    always random (unless some explicit logic is applied)
    and CPU can execute any thread at any time within the
    process. So the results you got are perfectly right.
    Even the order of the output may change everytime you
    run the same program.
    -- manishI think you can change the predictability by setting the Producer's thread priority has higher than the Consumer's...

  • Trying to learn about PL/SQL

    Have a problem I can not figure out in time. Anyone have any ideas?
    Write a PL/SQL program to compute the number of days in each month for year 2020. Your program will first create a table named Month_Days with two columns (see the table structure below). Use a Loop in your program to insert month and the number of days in that month into the table. INSERT INTO command can only be used once in your program. Your program should work correctly for any year.
    current version I am working on looks like this
    Set Serveroutput on;
    DROP TABLE MONTH_DAYS;
    CREATE TABLE MONTH_DAYS(
    Month_ Varchar(9),
         Days_ Number (2));
    Begin
    FOR i IN 1..12 LOOP
    INSERT INTO MONTH_DAYS (Month_, Days_)
    Values(to_char(to_date('i-01-2020','MM')), to_char(to_date(last_day('01-i-2020'),'DD')));
    DBMS_OUTPUT.PUT_LINE('Month_'||''|| 'Days_');
    end loop;
    end;

    Compute Number of days in each month of Year 2020
    DROP TABLE MONTH_DAYS;
    CREATE TABLE MONTH_DAYS(cnt number(2), Month_ Varchar(9),Days_ Number(2));
    declare
    mons Varchar2(10);
    dats Varchar2(10);
    begin
    for i in 0..11 loop
    insert into month_days(cnt, month_, days_)
    values
    (i,to_char(add_months(to_date('20200101','YYYYDDMM'),i),'Month'),
    to_char(last_day(add_months(to_date('20200101','YYYYDDMM'),i)),'DD'));
    select month_ , days_ into mons, dats from month_days where cnt = i;
    DBMS_OUTPUT.PUT_LINE('Month: '||Mons||'Days: '|| Dats);
    end loop;
    end;
    /

  • Trying to learn about Predictive Text

    My N8 User Guide (PDF) seems silent on how to use predictive text. Is it supposed to be so obvious that anyone can use it, and I'm an imbecile?
    My biggest gripe is that once predictive text finds what it thinks is a better word than the one I was spelling, I cannot find a way to convince it that I'm right. 
    In the interim, I've turned predictive text off, but it would be hugely beneficial to me. I teach English, so my spelling is above average, but my typing is carp.

    I have attached screenshots on how to deactivate predictive text. This taken using N8 running on Symbian Anna. Hope this helps
    Attachments:
    Anna 1.JPG ‏104 KB
    Anna.JPG ‏54 KB

  • Dumb question about Thread Safety in Servlets

    Hi all
    I wrote this Client API for sending requests and receiving responses to / from a multivalue database. The API is called by my Servlet. Now it seems my API is not thread safe because when several people open up the servlet at the same time, the API gets totally confused. When the API calls are inside a synchronized(){} it works just fine, but obviously at a big performance hit. Is that the wrong way of doing it??
    However when I was doing the ACID test locally on my machine, by opening two command prompts and excuting the same java program (with the same code in it as the servlet, but standalone) my API worked just fine. How come?
    Any insights appreciated as I am just learning about thread safety now (the hard way :-( )
    cheers
    Dejan

    Does this help
    Are you using one connection to the database shared by all instances
    of your servlet
    And is this connection create in the init method of the servlet and stored
    in the servlet context.
    Problem 4 people try and use your servlet at the same time, each servlet trys to
    create a connection to the database and then store it in the servlet context and
    this causes a problem.
    Solution create a listener to create the connection and store it in the servlet context
    when the servlet is created.
    If this is your problem it is not advisable to use only one connection to the db
    try using db pooling

  • Network storage drive...where can I learn about these?

    I have so many questions, and frankly, the answers I've seen looking (briefly, admittedly) around these threads scare me.  Gee, Wally, what ever happened to Apple as the computer you didn't have to know computer programming to use?
    Now, before you all get your panties in a bunch telling me that I'm responsible for knowing how to use my hardware, I know...and I do want to know.
    So what I want to know now is how can I learn about the various types of "shares", and what they mean for hooking up a network drive for backup, etc.
    I have a WD 1TB drive which I believe uses "SMB", whatever that is.  It's got two folders on it currently, "Public" which I can access, and "WD Backup", which I can't.  I also can't seem to use it as a Time Machine drive, which is what I want to do with it.  And, or course, I can't re-format it, which I'd love to do as my wife hates the folder designations on it, and would like to have one folder called "iMac Backup" on it.
    Answers which don't involve Terminal will get extra points, but I've dealt with Terminal before, so take your best shot.  And ask for clarification if you need it.  Thanks.

    Unfortunately, networking and file-sharing aren't quite so simple in part because there's decades of history and dozens of companies involved in getting it into the current state. If you want dead-simple, you can get an Apple Time Capsule or AirPort with an external drive and be done with it. However, if you really want the most from network storage, you'll probably want to read up...
    WD make a number of drive, some network-attached, some not. We'll assume that you have one of their basic consumer network-attached drives.
    "SMB" stands for "Server Message Block" protocol and it was the local area network file-sharing protocol developed for Windows for Workgroups circa 1992 (it was later renamed CIFS - Common Internet File System - by Microsoft in 1996 because of the rising popularity of the Internet, despite the difficulty in getting it to work in anything but a small local network). SMB/CIFS is still widely used today for Microsoft Windows networks, though much of the equipment that serves those files are built on Linux or FreeBSD and not Windows.
    Access to shares on an SMB server (such as your hard disk) is controlled through a configuration utility provided with the drive or via a web application built into the device (that you access through your browser). Consult your manual. Generally speaking, however, SMB servers offer different ways of identifying whether or not you can access a share: 1) based on the computer connecting (in which case, everyone is considered the same user), or 2) based on a username/password combo. Generally a server will only operate in one mode. Shared directories can also allow or deny "guest" access (access without a password). All of this should be configurable through the drive utility or web application which you access with your web browser. Generally, an SMB server can only operate in one mode.
    It sounds like the Public directory is configured to allow guest access, and I'm guessing that "WD Backup" is a share that's password-protected and intended to be used with Western-Digital's own software of the same name. You should be able to add and create new directories as necessary through the provided utility or the web interface.
    You are correct, you cannot use Time Machine with an SMB file-sharing service. Time Machine will require AFP (Apple Filing Protocol) or NFS (Network File System) support. Western-Digital only has 3 network drives that support AFP and Time Machine: My Book Live, MyBook World, and WD ShareSpace. OS X also has some basic requirements about the performance and capabilities of network storage in order to use it with Time Machine, so you really want to look for drives that state up front that you can use Time Machine with them (for example, WD World Edition: http://www.wdc.com/wdproducts/updates/docs/en/appletimemachine.pdf )
    I'm not sure why you can't reformat the drive. This is supported on all WD products (though, if you've moved a bunch of data to it already, perhaps it would be a hassle).
    You can do backups of your Mac over SMB, but it's complicated by the fact that SMB is quite old and isn't capable of storing information about the file permissions, ownership, etc. It will be reliable for data files, but not for applications, etc. There's a work-around, of course. You can create a disk image on the SMB share using Disk Utility (make sure you create an HFS+ image) and backup to that. If you go that route, I would suggest either Carbon Copy Cloner or SuperDuper to perform your backups. They are true backup tools, not versioning tools like Time Machine.

  • Where can i learn about Boot Camp

    to all
    i would like to learn about boot camp and the risks of puttiong windows on my mac. some things i just need on windows.
    where can i read about it before i start to post dumb questions about virus software and the risk of virus, as i'm sure its been addressed somewhere..

    thanks for the reply The Hatter... but its not a case of not leaving my comfort zone, but getting the full facts first for what i want to do. I;m quite good at leaving my comfort zone thank you..
    currently trying to build a server at home with little experience
    teaching myself HTML and Javascript and writing 5 websites on the fly
    among many other things.. i just need to find out more about what i am doing before i do it so i understand what i am doing, and whether its the best use of my time.
    my laptop most certainly doesn't sit on a shelf. its been around the world, to far flung corners of jungles, remote islands in Thailand and never leaves my side. Its on al day working and on all night processing. infact it almost drowned with me when i was caught in a violent storm going between islands in Thailand. Naturally i put the laptop somewhere safe before saving myself from going overboard.

  • I'm trying to learn and I think the knowledge is here!

    Hi! i'm always trying to learn and pass forward.  I'm not here to cause trouble. I have some things that I would like to have confirmed or denied. I do not own a HP computer at this time, but several of the residents in my village do. I have observed some great advice to community members from some smart people here on the forum. I have some things that I have learned from other forums and I want to share them. I would like to have comments from all the smart members here on the community forum. OK here we go!!
    Let's say we have a PC that won't boot into windows for some reason. Now IMHO, we have software or hardware problems.
    This is what I do. I down load a linux program. It's called Pupply Love.http://puppylinux.org/main/Overview%20and%20Getting%20Started.htm
    This is a ISO file that you burn to a CD. It is a live CD and you can boot with it. You do not need a HD.
    Even if your PC has no hard disk (ex, broken hard disk), you can still boot Puppy via CD or USB and continue working. Old PCs that no longer work with new systems will still work good-as-new with Puppy.
    Now IMHO, you have proved that your monitor,power supply, and CPU are working. So now the HD is left. There are many ways to test your HD. One that comes to my mind is seatools dos.http://www.seagate.com/support/downloads/item/seatools-dos-master/
    One way to test your memory is memtest86.http://www.memtest86.com/download.htm
    memtest and seatools dos are both live CD's and should boot even if you don't have a working OS.
    Another live CD is the system repair CD  and the system recovery discs that you should have created on day one.
    I realize that HP has some great tools and I'm hoping that a guru will reply to this thread and add their comments. This is the way I learn. Computers can be a pain in the neck, but us humans can hold our own if we are willing to learn and pass forward to others.
    Dokie!!
    PS I take criticisms pretty well! This thread can be deleted if it is out of line or does not meet the standards of the forum. Some times I get a little windy and carried away.

    Hi Leo! If you can stop these down load managers, you will be my hero.
    Dokie!!
    PS I have tried my best to warn members here on the forum, but I haven't got a lot of support so far.
    I have my figers crossed that the new team will get-er-done

  • I have had LR4 since last August.Have just decided to start using it.I have an IMAC 10.9.3 version. Am trying to learn with "Classroom in a Book. Ton of  problems.Adobe will not help because it is to old and they no longer support. Can anyone tell where I

    Did anyone see the post I made about LR 4?Just in case I will post again. I have LR4 I bought last August and just now I am trying to learn this >I have "Classroom in  a Book" for LR4 lots of problems . I have a IMAC version 10.9.3. I tried different Adobe sites. They will not give me the Time of day because they say they no longer support this program. Can anyone here tell me where I can get support for this LR$ that Adobe no longer recognizes. Thank you My name is Jerry S. MY e-mail is [email protected] and phone number is 563-344-7910.

    Okay I will try. First I have lost pictures in catalogs and could not find again.I have tried reinstalling LR4 and when I do and reopen LR4 the same catalog appears in the panel and filmstrip and I have no idea how to get rid of that catalog and start over at square one like it was the frist time it was opened. That would be a big help and I think I start over and avoid the same problems.

  • Hi, I've just started as a fresher in sap fico and I'm upto the LSMW part and I'm wondering why I keep getting an error in Run batch step when I do everything else correct could you help?  Please help I'm really trying to learn it as fast as possible

    Please help I'm really trying to learn it as fast as possible?  I've posted the file with all my screen shots going through the enitre process of me creating the LSMW file.

    First, I will try to address the iPod issue: If youve tried EVERYTHING on the website, your only other option is probably to contact Apple, I recommend by phone, and informing them of the problem. You are covered by warranty and therefore they are liable to assist you. Try that and come back with a status update
    Now I will address your attitude about it:Its absolutely understandable to be upset over something like this, especially with such an expensive product, but you are generalizing far to much. You may think Apple is being unproffesional by not warning potential buyers of the iPods common faults, but do you really think they would? they are out to sell these things, they arent going to point out the bad in their product. And not all iPods have problems, in fact only a fraction do. That gopes for the rest o Apples products as well. You are too hasty assuming all Apple products are junk, and one of many reasons as to why that is unfair of you is becuase you dont own any other Apple products.

  • I'm a newbie: I have a question about threads

    midp 2.0
    Java SE 5.0
    J2ME version 2.2
    Below is my code I'm stucked with..... The code here shows a midlet class
    and another class derived from Thread (NetworkThread). This NetworkThread
    gets started from the main midlet... Search my code for the term ??????? and
    there you find my trouble area... What I'm having trouble with is that at
    that point in my code a NetworkThread has been given a url to access, and
    putting network access in the main thread is a bad thing because one can
    never know how long it takes to access the server... I want this line:
    System.out.println("NETWORK COMMINUCATION DONE"); to be processed after
    NetworkThread is done requesting the url.... I'm not sure how to solve this
    code so that the midlet waits for NetworkThread to access the url... But
    while NetworkThread access the url I want the midlet to response to user
    input, I don't want it to look like the midlet has crashed......
    Any tips on how I can solve this issue will be greatly appreciated...
    By the way, if you see anything else that could have been improved in my
    code, then please tell me about it too....
    MY CODE:
    NETWORKTHREAD:
    package com.test;
    import java.io.IOException;
    import java.io.*;
    import java.util.*;
    import javax.microedition.io.*;
    public class NetworkThread extends Thread
    private boolean networkStop;
    private boolean networkPause;
    private HttpConnection httpConnection = null;
    private InputStream inputStream;
    private String Url;
    private String netCommand = null;
    private String netArg = null;
    private LoginForm loginForm;
    public NetworkThread(String serverURL)
      Url = serverURL;
    synchronized void requestStop()
      networkStop = true;
      notify();
    synchronized void resumeGame()
      networkPause = false;
      notify();
    synchronized void setCommand(String cmd, String arg)
      System.out.println("setCommand = " + cmd);
      netCommand = cmd;
      netArg = arg;
      networkPause = false;
      notify();
    void pauseThread()
      networkPause = true;
    public void run()
      networkPause = true;
      networkStop = false;
      while (true)
       if (networkStop) {
        break;
       synchronized(this) {
        while (networkPause) {
         try {
          wait();
         catch (Exception e) {}
       synchronized(this) {
         if (netCommand != null) {
           if (netCommand.equals("LOGIN")) {
             //Here some networking processing will
             //be done
         else if (netCommand.equals("LOGOUT")) {
         netCommand = null;
       pauseThread();
    THE MIDLET:
    package com.test;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.io.*;
    import java.io.IOException;
    import java.lang.String;
    public class Test extends MIDlet
      private Display display;
      private NetworkThread networkThread;
      private String Url;
      public Test() {
        display = Display.getDisplay(this);
      public void startApp() throws MIDletStateChangeException {
        if (networkThread == null) {
          networkThread = new NetworkThread(Url);
          networkThread.start();
      else {
         networkThread.start();
    public void destroyApp(boolean unconditional) throws
    MIDletStateChangeException {
       public void pauseApp() {
       public void commandAction(Command c, Displayable s) {
         if (c == okCommand) {
           networkThread.setCommand("LOGIN", "arg1");
           System.out.println("NETWORK COMMINUCATION DONE");
    }

    You will probably need to learn about HTTP and XML to complete this project. If you don't know Java at all then I would suggest starting with tutorials like these ones first
    http://java.sun.com/docs/books/tutorial/index.html
    Have a happy day.

  • Want to learn about xCode

    I bought my first Mac in february and I love everything about it. that said, I've been trying to get my hands on as much software as possible and I'm interested in learning about xCode. is there somewhere I can get started, right from scratch? I don't know much about developing software at all but I'm willing to learn.
    Thanks

    I posted this a while back. I don't know if it was helpful or not. It is a tutorial on C programming written by the author of a very good book on Motif programming.
    How C Programming Works
    Since you are just starting, my advice is to stay out of Xcode, just for little bit. Go through some basic "HelloWorld" tutorials. Learn how the terminal works. Learn a little bit about the process of compiling a source file into an executable. Xcode is very good, but it hides a lot of what is going on underneath. I think you would be much more effective with Xcode if you knew a little about that hidden stuff.

  • Learn about Tilt -- Notification

    This is in regards to viewing pictures (GALAXY S3)  when in the camera mode. the LEARN ABOUT TILT  notification keeps popping up, says cancel or enable.  Okay, so maybe I will enable, then I also go into my phone settings and yep it's enabled, no problem.   Back to Camera, view pic, dang if the LEARN ABOUT TILT notification AGAIN keeps popping up, then I have to tap done everytime.   IS there away to stop this.  I tried disabling motion features in phone setting, no luck.  Or is this the way it is, if so do not like it, NEVER happened before.  

    Try clearing data and cache for Gallery and then reboot your phone.  Sometimes Gallery remembers things that it shouldn't.
    Settings > Application manager > All > Gallery

  • How or where I can connect photoelectric sensors on 7350 controller or Mid-7604. Also where can I learn about basic wiring connection of sensors Thanks

    How or where I can connect photoelectric sensors on 7350 controller or Mid-7604. Also where can I learn about basic wiring connection  of sensors Thanks

    Hello Hassan,
    Thank you for using National Instruments Discussion Forum.  It looks like this is a duplicate post.  If it isn't I apologize and please repost to clarify.  Otherwise please use THIS thread for the discussion.
    Regards,
    Mark T
    Applications Engineer
    National Instruments

Maybe you are looking for

  • I will never complain about Creative products again...long story

    Two days ago I was a winy little #$%&* complaining about what my Zen Touch didn't do. It didn't support Audible, it didn't support Janus, has few accessories, blah, blah, blah. Then, it didn't do anything...it broke. So, in my infinite wisdom, I deci

  • Calling a Web Service from Java

    Our java guru (who is out sick....AHHHH) created all the calls that are needed to access the web service that he has running. For example the call getLongList(String user, String password) will return a list of all outstanding transactions. He made a

  • Randomise midi events in garageband?

    Hi. Anyone know of a plugin or method to randomise midi events in garageband? E.g. I'd like to be able to randomise (to a controlled degree) note velocities (preferably within a specified range perhaps ± one or two points) and note beginnings (± a fe

  • Advice:  Getting started in the digital editing

    What advice would you give someone with very limited experience, who wants to get started as an (paid) editor? (Other than don't do it.) My budget is $14K. What equipment? Groups?

  • Merging cells in Numbers

    Why can't I merge two cells on the same row when the first cell is in column A?