Java Multithreaded Learning Notes

Source: Internet
Author: User

Java Multithreading One, introduction

In general, the problem of concurrency outcomes can be broadly divided into "speed" and "design manageability".

    • Speed: Multithreading mechanism can be passed 频繁的线程间切换 , effectively avoid the 阻塞 "" problem;
    • Design manageability: That is, improve the code design, concurrent programming more in line with human practical logic, can effectively solve 仿真 related problems.
Second, Java thread 1. Create and start

There are usually two ways to create threads in Java:

    • Extended Java.lang.Thread Class

        public class taskT extends Thread{      public void run() {          System.out.println("正在执行Runnable!");      }      public static void main(String[] args) {          Thread t =new taskT();          t.start();      }  }
    • Implementing the Java.lang.Runnable Interface

        public class taskR implements Runnable{      @Override      public void run() {          System.out.println("正在执行Runnable!");      }  }  public static void main(String[] args) {      taskR r = new taskR();      Thread thread = new Thread(r);      thread.start();  }

Once a new thread is created and executed, that is, when the Start method is called, there is one more process in the virtual machine, which is parallel to the original process.

public class TaskR implements Runnable{    @Override    public void run() {        System.out.println("正在执行线程B!");        System.out.println("已经执行完线程B!");    }}public class test {    public static void main(String[] args) {        System.out.println("正在执行main函数111!");        TaskR b = new TaskR();        Thread threadB = new Thread(b);        System.out.println("准备添加线程B!");        threadB.start();        System.out.println("继续执行main函数222!");//      for (int i = 0; i < 999999; i++);//延时代码        System.out.println("正在执行main函数333!");    }}

The output of the above program execution result is as follows:

正在执行main函数111!准备添加线程B!继续执行main函数222!正在执行main函数333!正在执行线程B!已经执行完线程B!

Remove the comment code from the main function to increase the code delay and output as follows:

正在执行main函数111!准备添加线程B!继续执行main函数222!正在执行线程B!已经执行完线程B!正在执行main函数333!

Compared to the previous two groups, it is not difficult to find out that when thread threadb starts executing (executing threadbb.start ()), the main function of this thread and thread threadb is concurrent.

It is also important to note that the multi-threaded surface gives the impression that multiple tasks are carried out simultaneously, in fact not so, the virtual machine through the frequent switching process to give people the illusion of simultaneous execution.

2. Conversion of thread state

The state of a thread is the basis of thread control. The total thread state can be divided into five categories: health, waiting, blocking, sleep, death.

    • Raw: The thread has been new and has not been executed;
    • Start (): The thread calls the start () method to enter the waiting/running state;
    • Yield (): In addition, the executing thread can also make the current thread suspend execution through the Thread.yield () method and go into a running state, thereby yielding to other threads, but it may also fail because the thread may be re-selected after it enters the running state. (Note: The concession thread is followed by the execution of the thread, or re-execution, the program test is followed by execution of the code is not executed);
    • Blocking: The thread is stuck or not running, and cannot jump out of the run () method;
    • Sleep (): Call the Thread.Sleep () method, which causes the thread to pause for a period of time, that is, sleep, which can be used to help other processes get the chance to run;
    • Dead: The thread finishes executing and executes the run () method.
3. Synchronization and locking of threads

When multiple threads access mutually exclusive (exchangeable) data, they should be synchronized to protect the data, ensuring that two threads do not change it at the same time. Usually implemented in the synchronized field, and can only be synchronized with the method or synchronization code quickly.

If two threads are going to execute the synchronized method in a class, and two threads use the same instance to invoke the method, only one thread can execute the method at a time, and the other waits until the lock is freed.

4. Thread switching
    • Notify ()
    • Notifyall ()
    • Wait ()
5. Scheduling of threads
  • Hibernation: Thread.Sleep ()
  • Priority level
  • Concession: Thread.yield ()
  • Merge: Join (): the Join () method is to add a thread B to a thread A, and a must not execute until thread B is finished.

      public class Taskr implements runnable{@Override public void Run () {System.out.println ("executing thread B!          ");          try {thread.sleep (1000);          } catch (Interruptedexception e) {e.printstacktrace (); } System.out.println ("Thread B has finished executing!      "); }} public class Test {public static void main (string[] args) throws Interruptedexception {SYSTEM.OUT.PR INTLN ("Executing the main function!          ");          Taskr B = new Taskr ();          Thread threadb = new Thread (b); System.out.println ("Ready to add thread B!          ");          Threadb.start ();      SYSTEM.OUT.PRINTLN ("Finish main"); }} public class Test2 {public static void main (string[] args) throws Interruptedexception {SYSTEM.OUT.P RINTLN ("Executing the main function!          ");          Taskr B = new Taskr ();          Thread threadb = new Thread (b); System.out.println ("Ready to add thread B!          ");          Threadb.start ();          System.out.println ("Threadb.join ()");   Threadb.join ();       SYSTEM.OUT.PRINTLN ("Finish main"); }  }

    Executing the main execution results in Test1 and test2, respectively, is as follows:

      正在执行main函数!  准备添加线程B!  threadB.join()  执行完main  正在执行线程B!  已经执行完线程B!

    Add join () method in Test2:

      正在执行main函数!  准备添加线程B!  threadB.join()  正在执行线程B!  已经执行完线程B!  执行完main

    Sleep is called in threadb in order for the main function to get the execution opportunity. As a result, when THREADB calls the Join method, even if sleep does not run out of the main function, it demonstrates the role of the Join method, that is, it must threadb execution to continue executing the main function.

  • Daemon Threads
Thread pool

Java.util.concurrent.Executors. Cases:

ExecutorService pool = Executors.newFixedThreadPool(2);Thread t1 = new MyThread(); Thread t2 = new MyThread();Thread t3 = new MyThread();Thread t4 = new MyThread();pool.execute(t1);pool.execute(t2);pool.execute(t3);pool.execute(t4);pool.shutdown();

Java Multithreaded Learning Notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.