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)