Java Multithreading Basics (i)

Source: Internet
Author: User

An example of a simple multithreading:

 Packagemultithread; Public classBasicthreadImplementsrunnable{Private intCountdown = 10; Private Static intTaskcount = 0; Private Final intid = taskcount++;  Public Static voidmain (String [] args) {Thread T=NewThread (NewBasicthread ()); T.setname ("Test_thread1");   T.start (); //Not T.run (); T.run () would not start a new thread,just exist one threadSystem.out.println ("I am finished!"); } @Override Public voidrun () { while(countdown>=0) {System.out.print ("#" + ID + "(" + (countdown>0? Countdown: "Lift off!") + "),"); Countdown--; }            }    }

The result of the operation is:

I am finished! #0 (Ten), #0 (9), #0 (8), #0 (7), #0 (6), #0 (5), #0 (4), #0 (3), #0 (2), #0 (1), #0 (lift off!),

There are a few notes on the above code:

1.final int id = taskcount++,final The value is constant when the base variable is modified, and from the result you can see that the value of the ID is always 0.

2. Use T.start () to open a thread, not T.run (), T.run (), or a thread running in the main method, always having only 1 threads.

3. Use of T.setname ("Test_thread1"); is a good habit, easy to follow the positioning problem.

With Setdaemon (true), you can set a thread as a background thread, and the background thread has the following characteristics:

When only daemon threads are left in 1.JVM, the JVM will not exit as long as there is one Non-daemon thread surviving. Daemon threads can do some service work in the background, such as the JVM's GC thread is a low-priority daemon thread.

2. When the thread starts, the default is Non-daemon.

3.setDaemon (True) be sure to return the exception before the Start method.

4. A Non-daemon thread that has already started cannot be changed to a daemon thread.

A new thread that is generated in a 5.Daemon thread will be daemon by default.

  

Java Multithreading Basics (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.