Java Multithreading (i)

Source: Internet
Author: User

First, the understanding of the thread

1, the same application, a number of tasks at the same time. Just like QQ chat, open a chat window is a thread.

2, the thread can have multiple, but the CPU only do one thing every time. Because CPU processing is fast, we feel that we are doing it at the same time. So, on a macro level, threads are executed concurrently; from a microscopic point of view, threads execute asynchronously.

3, the purpose of using threads is to maximize the use of CPU resources. Think of QQ chat, if there is no multi-threading, a person's information is not sent out another person's information can not be sent over, what will be the situation ~!

Second, use threads in Java

 1. Creating Threads

EG1: Inherit thread

Class MyThread extends thread{    @Override public    void Run () {  //code    }}

Start Thread method: New MyThread (). Start ();

EG2: Implementing the Runnable Interface

Class Myrunnable implements Runnable {    @Override public    void Run () {        //code    }}

Start thread method: New Thread (new Myrunnable ()). Start ();

 2. Set Thread Priority

Thread t = new thread (myrunnable); t.setpriority (thread.max_priority);//Total 10 levels, thread.max_priority represents superlative 10
T.start ();

 3. Usage and difference of Join,sleep,yield

Join method: If you call the Join Method B.join () of the B thread in the a thread, then the B thread continues to run and a thread stops (into the blocking state). Wait for B to finish running a and then continue running.

Sleep method: When the sleep method is called in a thread, this thread stops (into a blocking state) and the run is handed over to the other thread.

Yield method: This thread does not stop when the yield method is called in a thread, and the run is snatched by this thread and the thread with priority not lower than this thread. (not necessarily high priority can be grabbed first, but high priority of the long time to rob)

 4. End Thread (modify identifier flag to false to terminate the running of the thread)

public class ThreadTest {public    static void Main (string[] args) {        a aa = new A ();        Thread tt = new Thread (AA);        Tt.start ();        try {            thread.sleep;        } catch (Exception e) {            e.printstacktrace ();        }        Aa.shutdown ();    }} Class A implements Runnable {    Private Boolean flag = true;    public void Run () {        while (flag) {            System.out.println ("AAAA");        }    }    public void ShutDown () {        This.flag = false;    }}

5. Thread synchronization Synchronized

Synchronized can modify a method, or a code block inside a method. A block of code that is synchronized decorated means that a thread does not allow other threads to manipulate the resource while it is manipulating the resource.

public class ThreadTest {public    static void Main (string[] args) {        myrunnable myrunnable = new myrunnable ();        New Thread (myrunnable). Start ();        New Thread (myrunnable). Start ();        New Thread (myrunnable). Start ();        New Thread (myrunnable). Start ();    }} Class Myrunnable implements Runnable {    private int i = 0;    @Override public    Void Run () {        while (true) {            sumnum ()        }    }    Private synchronized void Sumnum () {        if (I <) {            try {                thread.sleep ();                i + +;            } catch (Interruptedexception e) {                e.printstacktrace ();            }            System.out.println (Thread.CurrentThread (). GetName () + "--------"                    + i);}}}    

6. Usage of wait, notify, Notifyall

Wait method: The current thread goes into a blocking state, giving up control of the CPU and unlocking the lock.

Notify method: Wakes one of the threads because wait () enters the blocking state.

Notifyall method: Wakes all threads because wait () enters the blocking state.

All three methods must be wrapped in synchronized blocks, and must be the same lock, or the java.lang.IllegalMonitorStateException exception will be thrown.

Here is an example of a producer and consumer:

public class Productconsumer {public static int i = 0;        public static void Main (string[] args) {productstack PS = new Productstack ();        Product Product = new Product (PS);        New Thread (product). Start ();        Consumer Consumer = new Consumer (PS);    New Thread (consumer). Start ();     }}class Product implements Runnable {Productstack PS = null;    Product (Productstack PS) {this.ps = PS; } @Override public void Run () {while (true) {if (Productconsumer.i <) {PS            . push ();            }else{break;        }}}}class Consumer implements Runnable {Productstack PS = null;        Consumer (Productstack PS) {this.ps = PS; } @Override public void Run () {while (true) {if (Productconsumer.i <) {PS            . Pop ();            }else{break; }}}}class Productstack {boolean ispro = TruE            Public synchronized void push () {if (!ispro) {try {wait ();            } catch (Interruptedexception e) {e.printstacktrace ();        }} notifyall ();        productconsumer.i++;        System.out.print ("First" + Productconsumer.i + "products, producers:" + Thread.CurrentThread (). GetName ());        Ispro = false;        try {thread.sleep (int) math.random () * 200);        } catch (Interruptedexception e) {e.printstacktrace ();            }} public synchronized void Pop () {if (Ispro) {try {wait ()};            } catch (Interruptedexception e) {e.printstacktrace ();        }} notifyall ();        System.out.println (", Consumer:" + thread.currentthread (). GetName ());        Ispro = true;        try {thread.sleep (int) math.random () * 1000); } catch (Interruptedexception e) {e.printstacktrace ();        }    }} 

Java Multithreading (i)

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.