Java Thread multithreading

  • 2020-04-01 01:44:43
  • OfStack

The Thread There are two ways to create threads:

1. Define the class to inherit the Thread class, override the run method in the class, call the start method of the class object, start method starts the Thread, and call the run method. The Thread class is used to describe threads. This class defines a function run that stores the code the thread wants to run.

2. Define a class to implement the Runnable interface, override the methods in the Runnable interface, establish a Thread object through the Thread class, pass the subclass object of the Runnable interface as the actual parameter to the constructor of the Thread class, call the start method of the Thread class to start the Thread, and the Thread will call the run method in the subclass of the Runnable interface;

Implementing the interface Runnable in a way that avoids the limitations of single inheritance;

Thread T;

T.s etMaemon (true); // set thread as background thread; When all foreground threads end, the background thread automatically ends.

T.n otify (); // wake up the thread;

T.n otifyAll (); // wake up all threads;

T.i nterrupt (); // interrupt thread;

Thread.sleep (100); // pause the thread for 100 milliseconds

Synchronized: The default lock is itself, can also lock the custom object;

There must be two or more threads executing, multiple threads using the same lock, and only one thread running during synchronization must be guaranteed.

Judge synchronization: Make clear which code requires multi-threaded operation, make clear Shared data, and make clear which statements in the multi-threaded operation code are operating 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.p rintStackTrace ();
          }
          System.out.println(this.tostring () + "sale:" + tick--);
        }
      }
    }
  }

As above :tick is the Shared data, the operation tick needs to operate in synchronized, and synchroized is the ticket itself.

Waiting wake mechanism: When operating synchronous threads, the lock held by the thread they operate must be identified. Only the waiting thread on the same lock can be awakened by the notify on the same lock, and the thread in different locks cannot be awakened. (i.e. : wait and wake must be the same lock)


Related articles: