Home >Java >javaTutorial >Java multithreading and timers
1. Multi-threading in java:
Use the java.lang.Thread class or the java.lang.Runnable interface to write code to define, instantiate and start new threads.
A Thread class instance is just an object, like any other object in Java, has variables and methods, lives and dies on the heap.
In Java, each thread has a call stack. Even if no new threads are created in the program, the threads are still running in the background.
A Java application always starts running from the main() method. The main() method runs in a thread, which is called the main thread.
Once a new thread is created, a new call stack is generated.
Threads are generally divided into two categories: user threads and waiting threads.
When all user threads finish executing, the JVM automatically shuts down. However, the waiting thread is not independent of the JVM. The waiting thread is generally created by the operating system or the user.
Two ways to create a thread
1. Create a subclass of Thread and override the fun method.
2. Use Thread’s parameter-containing constructor, and the parameter is the Runnable() object.
[java]
//Example 1: (Inherit Thread class)
Threadthread1=newThread(){
@Override
publicvoidrun(){
...//The specific execution is omitted Code
}
};
//Example 2: (Implementing Runnable interface)
Threadthread2=newThread(newRunnable(){
@Override
publicvoidrun(){
…..// The code to be executed is omitted
}
});
The second method is more suitable for object-oriented thinking and more flexible, so the second method is generally used.
Both methods must rewrite the run method.
2. The two classes used to implement the timer function in JAVA are Timer and TimerTask. The Timer class is a class used to execute tasks. It accepts a TimerTask as a parameter. Timer has two modes for executing tasks. The most commonly used one is schedule, which can execute tasks in two ways: 1: At a certain time (Data ), 2: After a fixed time (int delay). Both methods can specify the frequency of task execution.
[java]
//An example of a timer:
publicstaticvoidmain(String[]args){
classMyTimerTaskextendsTimerTask{//Write an internal class to inherit the TimerTask class to implement the function of the timer
@Override
publicvoidrun(){
}
}
System.out.println(newDate().getSeconds());
newTimer().schedule(newMyTimerTask(),2000);//Create a timer
}
//Implementation A statement will be output every once in a while: and there will be different intervals for odd and even numbers.
For more articles related to ava multi-threading and timers, please pay attention to the PHP Chinese website!