[Java] Java based multithreading

Multithreading

Concept: A thread refers to a single sequential control flow in a process. Multiple threads can be concurrent in a process, and each thread executes different tasks in parallel.

Life cycle:

img

  • New status:

    After using the new keyword and the Thread class or its subclasses to create a thread object, the thread object is in a newly created state. It keeps this state until the program starts() this thread.

  • Ready state :

    When the thread object calls the start() method, the thread enters the ready state. The thread in the ready state is in the ready queue and waits for the scheduling of the thread scheduler in the JVM.

  • Running status :

    If the thread in the ready state acquires CPU resources, it can execute run() , and the thread is now in the running state. The thread in the running state is the most complicated, and it can become blocked, ready, and dead.

  • Blocked state :

    If a thread executes sleep (sleep), suspend (suspend) and other methods, after losing the occupied resources, the thread enters the blocking state from the running state. The ready state can be re-entered after the sleep time is up or the device resources are obtained. It can be divided into three types:

    • Waiting for blocking: The thread in the running state executes the wait() method to make the thread enter the waiting blocking state.
    • Synchronous blocking: The thread fails to acquire the synchronized synchronization lock (because the synchronization lock is occupied by other threads).
    • Other blocking: When an I/O request is issued by calling the thread's sleep() or join(), the thread will enter the blocking state. When the sleep() state times out, join() waits for the thread to terminate or time out, or the I/O processing is completed, the thread turns to the ready state again.
  • Death status :

    When a thread in the running state completes its task or other termination conditions occur, the thread switches to the termination state.

The priority of the thread:

The value range is 1 (Thread.MIN_PRIORITY)-10 (Thread.MAX_PRIORITY) .

By default, each thread is assigned a priority NORM_PRIORITY (5).

Thread creation:

  • By implementing the Runnable interface;
  • By inheriting the Thread class itself;
  • Create threads through Callable and Future.

1. By implementing the Runnable interface

class RunnableDemo implements Runnable {
    
    
   private Thread t;
   private String threadName;
   
   RunnableDemo( String name) {
    
    
      threadName = name;
      System.out.println("Creating " +  threadName );
   }
   
   public void run() {
    
    
      System.out.println("Running " +  threadName );
      try {
    
    
         for(int i = 4; i > 0; i--) {
    
    
            System.out.println("Thread: " + threadName + ", " + i);
            // 让线程睡眠一会
            Thread.sleep(50);
         }
      }catch (InterruptedException e) {
    
    
         System.out.println("Thread " +  threadName + " interrupted.");
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }
   
   public void start () {
    
    
      System.out.println("Starting " +  threadName );
      if (t == null) {
    
    
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}
 
public class TestThread {
    
    
 
   public static void main(String args[]) {
    
    
      RunnableDemo R1 = new RunnableDemo( "Thread-1");
      R1.start();
      
      RunnableDemo R2 = new RunnableDemo( "Thread-2");
      R2.start();
   }   
}

operation result:

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

2. Create a thread by inheriting Thread

class ThreadDemo extends Thread {
    
    
   private Thread t;
   private String threadName;
   
   ThreadDemo( String name) {
    
    
      threadName = name;
      System.out.println("Creating " +  threadName );
   }
   
   public void run() {
    
    
      System.out.println("Running " +  threadName );
      try {
    
    
         for(int i = 4; i > 0; i--) {
    
    
            System.out.println("Thread: " + threadName + ", " + i);
            // 让线程睡眠一会
            Thread.sleep(50);
         }
      }catch (InterruptedException e) {
    
    
         System.out.println("Thread " +  threadName + " interrupted.");
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }
   
   public void start () {
    
    
      System.out.println("Starting " +  threadName );
      if (t == null) {
    
    
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}
 
public class TestThread {
    
    
 
   public static void main(String args[]) {
    
    
      ThreadDemo T1 = new ThreadDemo( "Thread-1");
      T1.start();
      
      ThreadDemo T2 = new ThreadDemo( "Thread-2");
      T2.start();
   }   
}

operation result:

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Thread method

The following table lists some important methods of the Thread class:

Serial number Method description
1 public void start() makes the thread start executing; the Java virtual machine calls the run method of the thread.
2 public void run() If the thread is constructed using an independent Runnable object, call the run method of the Runnable object; otherwise, the method does nothing and returns.
3 public final void setName(String name) changes the thread name to make it the same as the parameter name.
4 public final void setPriority(int priority) changes the priority of the thread.
5 public final void setDaemon(boolean on) marks the thread as a daemon thread or a user thread.
6 The public final void join(long millisec) waits for the termination of this thread at most millis milliseconds.
7 public void interrupt() interrupts the thread.
8 public final boolean isAlive() test whether the thread is alive.

Test whether the thread is active. The above method is called by the Thread object. The following methods are static methods of the Thread class.

Serial number Method description
1 public static void yield() Suspend the currently executing thread object and execute other threads.
2 public static void sleep(long millisec) Sleeps (suspends execution) the currently executing thread within the specified number of milliseconds. This operation is affected by the precision and accuracy of the system timer and scheduler.
3 public static boolean holdsLock(Object x) returns true if and only if the current thread holds the monitor lock on the specified object.
4 public static Thread currentThread() returns a reference to the currently executing thread object.
5 public static void dumpStack() prints the stack trace of the current thread to the standard error stream.

Create a thread through Callable and Future:

  • \1. Create an implementation class of the Callable interface and implement the call() method. The call() method will be the thread execution body and have a return value.
  • \2. Create an instance of the Callable implementation class, and use the FutureTask class to wrap the Callable object. The FutureTask object encapsulates the return value of the call() method of the Callable object.
  • \3. Use the FutureTask object as the target of the Thread object to create and start a new thread.
  • \4. Call the get() method of the FutureTask object to get the return value after the execution of the child thread ends.

public class CallableThreadTest implements Callable<Integer> {
    
    
    public static void main(String[] args)  
    {
    
      
        CallableThreadTest ctt = new CallableThreadTest();  
        FutureTask<Integer> ft = new FutureTask<>(ctt);  
        for(int i = 0;i < 100;i++)  
        {
    
      
            System.out.println(Thread.currentThread().getName()+" 的循环变量i的值"+i);  
            if(i==20)  
            {
    
      
                new Thread(ft,"有返回值的线程").start();  
            }  
        }  
        try  
        {
    
      
            System.out.println("子线程的返回值:"+ft.get());  
        } catch (InterruptedException e)  
        {
    
      
            e.printStackTrace();  
        } catch (ExecutionException e)  
        {
    
      
            e.printStackTrace();  
        }  
  
    }
    @Override  
    public Integer call() throws Exception  
    {
    
      
        int i = 0;  
        for(;i<100;i++)  
        {
    
      
            System.out.println(Thread.currentThread().getName()+" "+i);  
        }  
        return i;  
    }  
}


Use anonymous inner classes to create threads:

/*
 * 匿名内部类的格式:
 */
public class ThreadDemo {
    
    
    public static void main(String[] args) {
    
    
        // 继承thread类实现多线程
        new Thread() {
    
    
            public void run() {
    
    
                for (int x = 0; x < 100; x++) {
    
    
                    System.out.println(Thread.currentThread().getName() + "--"
                            + x);
                }
            }
        }.start();
        ;

        // 实现runnable借口,创建多线程并启动
        new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                for (int x = 0; x < 100; x++) {
    
    
                    System.out.println(Thread.currentThread().getName() + "--"
                            + x);
                }
            }
        }) {
    
    
        }.start();

        // 更有难度的,在Thread匿名内部类的里面再一次重写run方法
        //在实际运行时的结果是 hello+x。以thread的run方法为准。但是此处无意义
        new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                // TODO Auto-generated method stub
                for (int x = 0; x < 100; x++) {
    
    
                    System.out.println("java" + "--" + x);
                }

            }
        }) {
    
    
            public void run() {
    
    
                for (int x = 0; x < 100; x++) {
    
    
                    System.out.println("hello" + "--" + x);
                }
            }
        }.start();
    }
}

*Disclaimer: This blog post is my study notes, refer to the rookie tutorial and other network resources, if infringement, please private message! *

Guess you like

Origin blog.csdn.net/qq_42380734/article/details/105387830