Java concurrent programming Learning 1 thread creation and timer usage
1. The relationship between threads in Java JDK is as follows:
publicinterface Runnable {public abstract void run();}
The Thread class has
public void run() { if (target != null) { target.run(); } }
Target is a runnable object.
The following are the T and Tread classes:
publicclass Thread implements Runnable {.......... }
Both T and read have an init method of various parameters for parameter initialization.
init(...);
We can see that when we pass in a runable object to a Thread constructor, as long as the object is not empty, the run method of the runable object is executed, it is more in line with object-oriented thinking. Recommended.
// Use an anonymous internal class to start the Thread in 1new Thread () {@ Overridepublic void run () {while (true) {try {Thread. sleep (1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();} System. out. println ("Thread" + Thread. currentThread (). getName () + "running ");}};}. start (); // use an anonymous internal class to start the Thread in 2new Thread (new Runnable () {@ Overridepublic void run () {while (true) {try {Thread. sleep (1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();} System. out. println ("Thread" + Thread. currentThread (). getName () + "running ");}}}). start ();
Or define the child class of the thread to re-write the run method, and then define the start method of the object. Either implement the runable interface subclass (the run method of the rewrite subclass is an object of the thread to do) and pass it as a parameter to the thread constructor, then, the start method of the Child-Class Object of the thread is called to make the thread running and wait for scheduling.
Note: An object first executes the method of the object or operates on the attributes of the object. If the object does not exist, the parent class is considered. A subclass has the same method as a parent class. A subclass overwrites the parent class and only executes the method with the same name as a subclass.
Running result:
2. Timer usage <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + o6gxo6nDv7j0M3PUy9DQ0ru0zjwvcD4KPHA + PHByZSBjbGFzcz0 = "brush: java;"> new Timer (). schedule (new TimerTask () {@ Overridepublic void run () {System. out. println ("the scheduled task is running );
(2) scheduled tasks are alternate and designed according to the specific business logic.
New Timer (). schedule (new TimerTask () {@ Overridepublic void run () {System. out. println ("scheduled task 11111 running"); new Timer (). schedule (new TimerTask () {@ Overridepublic void run () {System. out. println ("scheduled task 2222 running );
Running result: