Java Learning Diary-----Multithreading

Common methods of Thread:
* 1.start(); start the thread and execute the corresponding run() method
* 2.run(); the code method to be executed by the child thread such as run(); within
* 3.currentThread() static Call the current process
* 4.getName()
* 5.setName()
* 6.yield() The thread calling this method releases the right to use the cpu
* 7.join(); a.join(), indicating that the current a thread stops Execute, until another thread finishes executing, process a will continue to execute the code after join()
* 8.isAlive() to determine whether the thread is still alive
* 9.sleep(long l): Show the current thread to sleep for l milliseconds
* 10. Thread communication: wait() notify() notifyAll()
*
*
* Set the priority of the thread setPriority

 

Create thread:

   ①: Inherit the Thread class

/*
 * Create a subclass of subprocess to complete the output of natural numbers between 1-100. Likewise, the main thread performs the same operation
 *
 * The first way to create multi-threads: Inherit the java.lang.Thread class
 */ 
// 1. Create a subclass that inherits Thread 
class SubThread extends Thread{
     // 2. Rewrite the run() method of the Thread class, and implement the function to be completed by the second child thread in the method 
    public  void run() {
         for ( int i =0;i<=100;i++ ) {
            System.out.println(Thread.currentThread().getName()+":"+i);
        }
    }
}
public  class TestThread {
     public  static  void main(String[] args) {
         // 3. Create a subclass object 
        SubThread st1 = new SubThread();
        SubThread st2 = new SubThread();
         // Start this thread: call the corresponding run() method; then call the run() method
         // A thread can only execute the start() method once
         // The run of class objects cannot be implemented through Thread () to start a thread 
        st1.start();
        st2.start();
        
        for(int i =0;i<=100;i++) {
            System.out.println(Thread.currentThread().getName()+":"+i);
        }
    }
}

 

  ②: Create a process by implementing the Runnable interface

// Use the method of implementing the Runnable interface to sell tickets 
/* 
class Window1 implements Runnable{
     int ticket = 100 ; 
     public  void run() {
         while ( true ){
             if (ticket > 0 ) {
                 try {
                    Thread.currentThread().sleep(10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "Ticket: Ticket number is:"
                        + ticket-- );
            }else {
                break;
            }
        }
    }
}
public class TestWindow1 {
    public static void main(String[] args) {
        Window1 w = new Window1();
        Thread t1 =new Thread(w);
        Thread t2 =new Thread(w);
        Thread t3 =new Thread(w);
        
        t1.setName( "Window 1" );
        t2.setName( "Window 2" );
        t3.setName( "Window 3" );
        
        t1.start();
        t2.start();
        t3.start();
    }
}
There is a security problem in this program, and there will be heavy or wrong tickets when printing tickets.
  1. The reason for the existence of thread safety problems?
         In the process of operating the shared data, another thread participates in the process of operating the shared data, and another thread participates, resulting in a security problem in the shared data.
  
  2. How to solve the thread safety problem?
          After a thread has finished operating the shared data, other threads have the opportunity to participate in the operation of the shared data.
  
  3. How does java achieve thread safety: thread synchronization mechanism
  
         Method 1: Synchronized code block (synchronization mechanism)
             synchronized(synchronized monitor) {
                  // The code block that needs to be synchronized ()
          }
  ①. Shared data: the same data (variable) that multiple threads operate together
  ②. Synchronization Monitor: Acted by an object of a class. Whichever thread gets this monitor executes the synchronized code in the curly braces. Common name: lock
          Method 2: Synchronous method

    Declare methods that operate on shared data as synchronized. That is, this method is a synchronous method, which ensures that when one thread executes this method,
    other threads wait outside until this thread finishes executing this method.
    > The lock of the synchronization method: this
4. Disadvantages of thread synchronization: Since only one thread can access the shared data at the same time, the efficiency is not high.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324936462&siteId=291194637