Java multithreading and java multithreading instances

Source: Internet
Author: User

Java multithreading and java multithreading instances

1. multithreading Overview

When a program runs, it may contain multiple sequential execution streams. Each sequential execution stream is a thread. It has the following advantages:

  • It is easy to implement shared memory between threads.
  • Low thread creation cost
  • Java built-in multithreading support
2. Thread creation and startupAll Thread objects are objects of the Thread class or its subclass. Each Thread completes a certain task. Java defines two ways to create a Thread: Method 1: Inherit the Thread class to create a Thread class

Define the subclass of Thread and override the run method.

Create an instance of the Thread subclass, that is, a Thread object is created.

Use the start method of the thread object to start the thread.

 1 public class DemoThread extends Thread 2 { 3     private int i; 4     String name; 5     public DemoThread(String name) 6     { 7         super(name); 8     } 9     public void run()10     {11         for(;i<100;i++)12         System.out.println(Thread.currentThread().getName()+"-------"+i);13         14     }15     public static void main(String[] args)16     {17         for(int i=0;i<100;i++)18         {19             System.out.println(Thread.currentThread().getName()+"-----------"+i);20         21             if(i==20)22             {23                 new DemoThread("windows1").start();24                 new DemoThread("windows2").start();25             }26         }27     }28 }
Method 2: implement the Runnable interface to create a Thread class

Define the implementation class of the Runnable interface and override the run method of the interface (this method is the thread execution body of the thread)

Create a Runnable implementation class instance and use this instance as the target of Thread to create a Tread object

 1 public class DemoThread implements Runnable 2 { 3     private int i; 4     public void run() 5     { 6         for(;i<100;i++) 7         System.out.println(Thread.currentThread().getName()+"-------"+i); 8          9     }10     public static void main(String[] args)11     {12         for(int i=0;i<100;i++)13         {14             System.out.println(Thread.currentThread().getName()+"-----------"+i);15         16             if(i==20)17             {18                 DemoThread t=new DemoThread();19                 new Thread(t,"Windows1").start();20                 new Thread(t,"Windows2").start();21             }22         }23     }24 }

Comparison of the two methods:

3. Thread LifecycleAfter a thread is created and started, it must go through five states: New, Runnable, Running, Blocked, and Dead ). New: After a thread is created with the keyword "new", it is in the new State. At this time, only the VM allocates memory for the thread and initializes the member variable. The program does not execute the thread execution body. Ready: When the thread object calls the start () method, the thread is ready. The virtual machine creates the call stack and program counter for the thread, but the thread is not running at this time, it indicates that the thread can run. Run: When the ready thread obtains the CPU and starts to run the run method, the thread is running. Blocking: When a thread calls the sleep method, the blocking I/O method, the suspend method, and the wait y method, the thread is nearly congested. The blocking status enters the ready status again when appropriate. Death: The thread ends in the following three ways, and is then in the dead state. The run method is completed, the thread throws an uncaptured exception, and the stop method is directly jumped to terminate the process. 4. thread controlIsAlive (): test whether the thread is active isDaemo (): test whether the process is a daemon join (): Wait for the process to terminate sleep (): sleep the running thread within a specified millisecond. This thread does not lose the ownership of any monitor. yield (): Pause the currently running thread object and execute other threads, it transfers the thread to the ready state setPriority (int newPriority): changes the priority of the thread   5. Thread Synchronization
When two or more threads need to access the same shared resource, some method is required to ensure that the resource is used by only one thread at a certain time. This method is called "synchronization". To solve the synchronization problem, java introduces the synchronization monitor. The code block format is as follows:
synchronized (obj){}
Java also uses the Synchronized keyword to modify a method. This method does not need to display the specified synchronization monitor.
Synchronization lock: it has and uses synchronizedThe method and the implicit monitor lock accessed by the statement have the same basic behavior and semantics, but are more powerful. The code format of the Lock object is as follows:
1 public class X 2 {3 private final ReentrantLock lock = new ReentrantLock (); 4 public void m () 5 {6 lock. lock (); // lock 7 try 8 {9 // code 10 to ensure thread security} 11 finally12 {13 lock. unlock (); // release lock 14} 15} 16} 17
6. Thread CommunicationJava implements in-process communication through the wait (), notify (), and notifyAll () methods to avoid polling detection.
Wait (): tells the calling thread to discard the monitor from entering the waiting mode until other threads enter the same monitor and calls the notify () method. Y (): Wake up a single thread waiting on this synchronization machine notifyAll (): Wake up all threads waiting on this synchronization Machine
  7. Thread PoolThe thread pool creates a large number of Idle threads when the system starts. The program sends a Runnable object to the thread pool, and the thread pool starts a thread to execute the run method of the object, after the run method is executed, the thread does not die. Instead, it returns the idle state in the thread pool again, waiting for the execution of the run method of the next Runnable object. To use a thread pool to execute a thread task, follow these steps:
  • Call the static factory method of the Executors class to create an ExecutorService object, which represents a thread pool.
  • Create a Runnable implementation class or Callable implementation class instance to execute tasks as a thread.
  • Call the submit method of the ExecutorService object to submit the Runnable instance or Callable instance.
  • Call the shutdown method of the ExecutorService object to close the thread pool when you do not want to submit any tasks.
Eg:
1 class TestThread implements Runnable 2 {3 public void run () 4 {5 for (int I = 0; I <50; I ++) 6 {7 System. out. println (Thread. currentThread (). getName () + "---" + I); 8} 9} 10} 11 public class TestMain12 {13 14 public static void main (String [] args) 15 {16 // The method stub automatically generated by TODO 17 TestThread t = new TestThread (); 18 ExecutorService pool = Executors. newFixedThreadPool (6); 19 pool. submit (new Thread (t); 20 pool. submit (new Thread (t); 21 pool. shutdown (); 22} 23 24}
Execution result:

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.