Java thread Basics

Source: Internet
Author: User
Basic knowledge of processes and threads

Process: A running application is called a process and has system resources (cpu and memory)
Thread:A piece of code in the processA process can contain multiple pieces of code. Does not own resources (share resources of the process)
In java, the program entry is automatically created as the main thread, and multiple subthreads can be created in the main thread.
Differences: 1. Resource occupation
2. The overhead required to create or cancel a process is greater than that required to create or cancel a thread.

3. The process is a heavyweight component and the thread is a lightweight component.

Multi-process: multiple tasks (programs) can be run simultaneously in the operating system)

Multithreading: multiple function streams are executed simultaneously in the same application.

Main advantages of multithreading (concurrent running of multiple threads)
This can reduce the bottleneck of system performance because it can be operated in parallel;

Improves the efficiency of CPU processors. In multithreading, priority management can give priority to important programs and improve the flexibility of task management. On the other hand, in multiple CPU Systems, different threads can be executed in different CPUs to truly process multiple tasks at the same time.

There are two ways to create a Thread: Inherit the Thread class or implement the Runnable interface.

First:

class MyThread extends Thread{public MyThread(String name) {super(name);}@Overridepublic void run() {for(int i=0;i<40;i++)System.out.println(i);}}public class Main {public static void main(String[] args) {MyThread m=new MyThread("myThread");m.start();System.out.println("main");}}

Second:

// To implement multithreading in java, the first is to continue the Thread class and the other is to implement the Runable interface. Class MyDemo implements Runnable {@ Overridepublic void run () {for (int I = 0; I <40; I ++) System. out. println ("run ----" + I) ;}} public class Deamo {public static void main (String [] args) {Thread t = new Thread (new MyDemo ()); // create thread t. start (); // start the thread. The thread enters the ready state and waits for the call. // t. run (); // No call is required. When a thread is called, The for (int I = 0; I <40; I ++) System is executed. out. println ("main ----" + I); // The running result may be an alternate execution of main/run }}

Thread status:

New status
After a thread object is created, the thread object is in the new State. A thread in the new State has its own memory space. by calling the start method, it enters the ready state (runnable ).
Readiness status
A ready thread has run conditions but has not been allocated to the CPU. Wait for the system to allocate the CPU to it. Once the CPU is obtained, the thread enters the running state and automatically calls its own run method.
Death status
The dead state is the last stage in the thread lifecycle. There are two reasons for thread death: one is that a normal running thread has completed all of its work; the other is that the thread is forcibly terminated, such as terminating a thread by executing the stop or destroy method.

When a thread enters the dead state, it cannot return to another State. By querying the API, we can see that the stop method and destory method are outdated, so they cannot be reused. What should we do to forcibly destroy a thread?
1. Execution of the return thread in the run method also ends.
2. You can set a flag in the while LOOP condition. When it is equal to false, the while loop will not run, so that the thread will end. Sample Code for implementation:

Public class MyRunable implements Runnable {private boolean isStop; // public void run () {while (! IsStop) System. out. println ("invoke MyRunable run method");} public void stop () {// stop thread isStop = true;} public static void main (String [] args) {MyRunable myRunable = new MyRunable (); Thread thread = new Thread (myRunable); thread. start (); try {Thread. sleep (5000);} catch (InterruptedException e) {e. printStackTrace ();} myRunable. stop (); // correct method for stopping a thread }}

Blocking status
A running thread, for example, executes the sleep (sleep) method or waits for resources such as I/O devices, will temporarily stop running the CPU, enter the blocking status.
The thread in the blocking status cannot enter the ready queue. Only when the cause of blocking is eliminated, such as the sleep time is reached, or the waiting I/O device is idle, the thread enters the ready state and waits in the ready queue again, after being selected by the system, it starts to run from the stopped position.

Class MyDemo implements Runnable {@ Overridepublic void run () {for (int I = 0; I <40; I ++) {System. out. println ("run ----" + I) ;}} public class Deamo {public static void main (String [] args) {Thread t = new Thread (new MyDemo ()); t. start (); then SC = new then (System. in); SC. next (); // wait for the input. The main thread is blocked }}

The above program first executes the content in run, and finally ends with a string
Thread Synchronization
Because multiple threads of the same process share the same storage space, it brings convenience and access conflicts. To prevent simultaneous access to shared resources, the thread can lock and unlock the resource before and after it uses the resource. In Java, due to multi-thread support, the following methods are used to control synchronization: synchronized, wait (), Policy (), and policyall ()

Each java object has a lock. When multiple threads access Shared resources at the same time, Synchronize is required to control the security. synchronize divides the synchronize method and synchronize block into only the content in the lock, other threads can be executed, atomicity

Let's take an example. The four windows sell 100 tickets at the same time, and tickets share data.

Class MyDemo implements Runnable {private int tickets = 100; @ Overridepublic void run () {while (tickets> 0) {try {Thread. sleep (1000); // ----------- catch (InterruptedException e) {e. printStackTrace ();} System. out. println (Thread. currentThread (). getName () + ": No." + (tickets --) + "tickets") ;}} public class Deamo {public static void main (String [] args) {MyDemo my = new MyDemo (); Thread t = new Thread (my), t1 = new Thread (my), t2 = new Thread (my ), t3 = new Thread (my); t. start (); t1.start (); t2.start (); t3.start ();}}

Thread-0: 3rd tickets
Thread-1: 2nd tickets
Thread-3: 1st tickets
Thread-1: 0th tickets
Thread-0:-2 tickets
Thread-2:-1 ticket
This is the sale of the last few of them, with a negative number. That is to say, when thread 1 is set up, the other one gets the execution in a certain period within the loop, an error may occur when thread 1 is executed again.

Synchronous Code block: synchronized (object) {---- content to be synchronized, generally used for shared resources --} the object can be any object,But several threads must be the same thread.

So the above example is changed:

Class MyDemo implements Runnable {private int tickets = 100; Object obj = new Object (); // The above is the shared resource public void run () in the program () {// Object obj = new Object (); it cannot be placed here, because each thread has its own run method. If the Object obj to be locked is not the same here, in this case, the synchronization effect cannot be reached. synchronized (obj) {// a Thread without a lock cannot enter while (tickets> 0) {try {Thread even if it obtains the cpu execution permission. sleep (100); // ----------- catch (InterruptedException e) {e. printStackTrace ();} System. out. println (Thread. currentThread (). getName () + ": No." + (tickets --) + "tickets") ;}}} public class Deamo {public static void main (String [] args) {MyDemo my = new MyDemo (); Thread t = new Thread (my), t1 = new Thread (my), t2 = new Thread (my ), t3 = new Thread (my); t. start (); t1.start (); t2.start (); t3.start (); // start four threads simultaneously }}

Synchronous method, that is, add synchronized before the method to public synchronized void run (){}

The synchronized keyword cannot be inherited. That is to say, the method of the base class synchronized f () {} is not automatically synchronized f () {} in the inheritance class, but is changed to f () {}. You must explicitly specify a method of the inherited class as the synchronized method.

No matter whether the synchronized keyword is applied to methods or objects, the lock it acquires is an object, instead of using a piece of code or function as a lock-and the synchronization method may be accessed by objects in other threads.

Which lock does synchronous function call have? If a function needs to be called by an object, all functions have an object reference, that is, this, so the lock used by the synchronous function is this

Verification is as follows:

Class Ticket implements Runnable {private int ticket = 100; Object obj = new Object (); boolean flag = true; public void run () {if (flag) {while (true) {synchronized (this) // two threads use the same lock. if the lock is safely changed to obj, two locks are used: incomplete {if (ticket> 0) {try {Thread. sleep (10);} catch (Exception e) {} System. out. println (Thread. currentThread (). getName () + "--- sale" + ticket --) ;}}} elsewhile (true) show () ;}public synchronized void show () {if (ticket> 0) {try {Thread. sleep (10);} catch (Exception e) {} System. out. println (Thread. currentThread (). getName () + "---- show ---" + ticket --) ;}} class Test {public static void main (String [] args) {Ticket t = new Ticket (); thread t1 = new Thread (t); Thread t2 = new Thread (t); t1.start (); try {Thread. sleep (10);} catch (Exception e) {} t. flag = false; t2.start ();}}

If the synchronous function is a static function, what is the lock used? This is not the case because this cannot be defined in static methods. When static data is imported into the memory, there is no such object in the memory, but there must be a corresponding bytecode file object for this class: Class Name. class the object type is Class, static synchronization method, the lock used is the bytecode file object of the class where the method is located: Class Name. class, static method internal synchronization code block can only use the class name. class Object

Verification:

Class Ticket implements Runnable {private static int ticket = 100; Object obj = new Object (); boolean flag = true; public void run () {if (flag) {while (true) {synchronized (Ticket. class) // two threads use the same lock. if the lock is safely changed to obj, two locks are used: incomplete {if (ticket> 0) {try {Thread. sleep (10);} catch (Exception e) {} System. out. println (Thread. currentThread (). getName () + "--- sale" + ticket --) ;}}} elsewhile (true) show ();} public static synchronized void show () {if (ticket> 0) {try {Thread. sleep (10);} catch (Exception e) {} System. out. println (Thread. currentThread (). getName () + "---- show ---" + ticket --) ;}} class Test {public static void main (String [] args) {Ticket t = new Ticket (); thread t1 = new Thread (t); Thread t2 = new Thread (t); t1.start (); try {Thread. sleep (10);} catch (Exception e) {} t. flag = false; t2.start ();}}


The following is the application of multithreading In the singleton design mode:

The Singleton mode is divided into: hungry and lazy

Ele. Me: multithreading does not exist.

class Single{private static final Single s=new Single();public static Single getS() {return s;}}

Lazy style:

Class Single {// The instance delays loading private static Single s = null; // note that the final public static Single getS () cannot be used here {// due to multithreading, the generated instance may not be one, so the synchronization mechanism if (s = null) {synchronized (Single. class) {// here, the static method can only be Single. classreturn new Single () ;}} return s ;}}

Thread priority:

Similar to thread sleep, the thread priority still cannot guarantee the thread execution order. However, a thread with a higher priority has a higher probability of obtaining CPU resources. A thread with a lower priority does not have the chance to execute the task.

The priority of a Java Thread is an integer. The value range is 1 (Thread. MIN_PRIORITY)-10 (Thread. MAX_PRIORITY ). The comment on NORM_PRIORITY (value: 5) in the Thread source code is "Default Thread priority"

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.