java multithreaded Thread implementation method code details

  • 2020-11-30 08:23:06
  • OfStack

The use of multithreading in java has been briefly introduced before, including Thread class and Runnable class. In order to better understand multithreading, this paper will analyze Thread in detail.

start()

Let's take a look at the introduction to this method in API:

Causes the thread to begin execution; The Java virtual machine calls the run method for this thread.

The result is two threads running concurrently; The current thread (returned to the start method from the call) and another thread (executed its run method).

It is illegal to start one thread more than once. In particular, a thread cannot be restarted after it has finished executing.

The start method is used to start the thread, which really realizes the multi-thread running. At this time, there is no need to wait for the body code of the run method to finish executing and directly continue to execute the following code. By calling the start Thread class () method to start a thread, then this thread in the ready state (run), and is not running, 1 denier cpu time, began to perform run () method, this method run () called a thread, it contains the contents of this thread to execute, Run method run over, immediately terminate this thread.

The start method is used to start the thread, and using java will create a new thread to execute the method in run. Here's a little demo:


    for(int i=0;i<3;i++){
      Thread t= new Thread(new Runnable() {
        @Override
        public void run() {
      System.out.println(Thread.currentThread().getName()+" start");
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
      System.out.println(Thread.currentThread().getName()+" end");
        }
      });
      t.start();
    }
    System.out.println("it is over");

Execution Results:
it is over
Thread-1 start
Thread-0 start
Thread-2 start
Thread-0 end
Thread-1 end
Thread-2 end

Since multithreading is random, the result may not be the same each time, which is also important to note that the execution order and calling order of the threads are not 1.

run()

The run method is to call the run method of Runnable set by Thread and modify the above demo:


    for(int i=0;i<3;i++){
      Thread t= new Thread(new Runnable() {
        
        @Override
        public void run() {
      System.out.println(Thread.currentThread().getName()+" start");
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
      System.out.println(Thread.currentThread().getName()+" end");
        }
      });
      t.run();
    }
    System.out.println("it is over");

Execution Results:
main start
main end
main start
main end
main start
main end
it is over
The direct result of the run method is very different from start in that it is executed entirely sequentially and no new threads are started.

stop()

The stop method, which forces a thread to stop execution, is unsafe and should not be used. When stop is called, the locked resource is released, but this release is non-1 and can cause program problems. If you want to control the stop of a thread, you can use a custom variable or the isInterrupted() method:


class Thread1 extends Thread {
  @Override
  public void run() {
    // Determines whether the thread body is running 
    while (!isInterrupted()) {
      // Do Something
    }
  }  
}

interrupt()

The interrupt function is to notify the thread that you have been interrupted, but the specific interrupt execution needs to be custom handled in the thread, and you can even continue the execution regardless. The specific middle loneliness is when the thread executes the join, wait, sleep methods, it throws InterruptedException.


Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+" start");
            try {
              for(int i=0;i<100000;i++){
                System.out.println(i+"");
                Thread.sleep(1);
              }
            } catch (InterruptedException e) {
              System.out.println("the thread is interrupted");// You can do resource release, logging, etc 
              e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" end");
          }
      });
      t1.start();
      Thread.sleep(100);
      t1.interrupt();

Execution Results:


65
66
67
68
the thread is interrupted
java.lang.InterruptedException: sleep interrupted
Thread-0 end
  at java.lang.Thread.sleep(Native Method)
  at com.wk.aqi.act.Test$1.run(Test.java:23)
  at java.lang.Thread.run(Thread.java:745)

isInterrupted()

To determine if the thread is broken, after executing the interrupt method above, return true.

setPriority (int newPriority) and getPriority ()
Setting the thread priority and getting the thread priority, cpu allocates resources to threads that focus on priority high.


Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            long t = System.currentTimeMillis();
            System.out.println(Thread.currentThread().getName()+" start");
            for(int i=0;i<1000;i++){
              try {
                Thread.sleep(1);
              } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              }
            }
            System.out.println(Thread.currentThread().getName()+" t1 end "+(System.currentTimeMillis()-t));
          }
      });
      Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
          long t = System.currentTimeMillis();
          System.out.println(Thread.currentThread().getName()+" start");
          for(int i=0;i<1000;i++){
            try {
              Thread.sleep(1);
            } catch (InterruptedException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
          System.out.println(Thread.currentThread().getName()+" t2 end "+(System.currentTimeMillis()-t));
        }
      });
      t1.setPriority(10);
      t2.setPriority(1);
      t2.start();
      t1.start();

Execution Results:


Thread-0 start
Thread-1 start
Thread-0 t1 end 1357
Thread-1 t2 end 1371

In the case of 1 priority, t1 and t2 are completed almost simultaneously. In the case of not 1 priority, there is a significant difference.

getName()

Simply, get the name of the thread.

join () and join (long millis)

The jion method waits for the thread to complete, and join(long millis) can set the maximum wait time. The join method can be used when the main thread waits for the child thread to complete and gets the result of the child thread before proceeding


Thread t1 = new Thread(new Runnable() {
      @Override
      public void run() {
          long t = System.currentTimeMillis();
          System.out.println(Thread.currentThread().getName()+" start");
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          System.out.println(Thread.currentThread().getName()+" t1 end "+(System.currentTimeMillis()-t));
        }
    });
    t1.start();
    t1.join();
    System.out.println(" Waiting for the t1 Execute it. Execute it ");

Execution Results:


Thread-0 start
Thread-0 t1 end 1001
 Waiting for the t1 Execute it. Execute it 

conclusion

Above is this article on java multithreaded Thread implementation method code details all content, hope to be helpful to you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out.


Related articles: