1. Define a class that inherits the Thread class, overrides the run method in the class, calls the start method of the class object, the start method starts the thread, and calls the run method. The Thread class is used to describe threads; this class defines a function run, which is used to store the code to be run by the thread.
2. Define a class to implement the Runnable interface, override the methods in the Runnable interface, create a thread object through the Thread class, pass the subclass object of the Runnable interface as an actual parameter to the constructor of the Thread class, and call the start method of the Thread class to start the thread. The run method in the Runnable interface subclass will be called;
The way to implement the interface Runnable avoids the limitations caused by single inheritance;
Thread T;
T.setMaemon(true);//Set the thread as a background thread; the background thread automatically ends when all foreground threads end;
T.notify();//Wake up this thread;
T.notifyAll();//Wake up all threads;
T.interrupt();//Interrupt thread;
Thread.sleep(100);//Pause the thread for 100 milliseconds
synchronized: By default, it locks itself, and custom objects can also be locked;
There must be two or more threads executing. Multiple threads use the same lock. It must be ensured that only one thread is running during the synchronization process;
Determine synchronization: clarify which codes require multi-threaded running, clarify shared data, and clarify which statements in multi-threaded running code operate on shared data;
class Tickets implements Runnable
{
private int tick = 100;
public void run() { // public synchronized void run()
while (tick > 0) {
synchronized (this) {
if (tick > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.toString() + "sale:" + tick--);
}
}
}
}
As above: ticks are shared data. To operate ticks, you need to operate in synchronized. What synchroized locks is the Tickets themselves;
Waiting wake-up mechanism: When operating synchronization threads, they must identify the locks held by the threads they operate. Only the waiting threads on the same lock can be awakened by notify on the same lock. Different locks cannot be The thread in wakes up; (that is: waiting and waking up must be the same lock)