Java multi-thread operations and java multi-thread operations

Source: Internet
Author: User

Java multi-thread operations and java multi-thread operations
Java threads

To run a program, you need to start an application process. A process can create multiple threads to help the application complete multi-task operations and run concurrently. In Java, threads are encapsulatedThreadClass, only oneThreadClass to implement your own functions, and then enable this thread, or you can implementRunnableInterface, and then pass itThreadObject, and then start it.

Thread creation and startup inheritance Thread

Create a class and inheritThreadClass, and then implementThreadClassrunMethod, inrunEnter your own code in the method, create the custom class, and call itsstartTo start the custom thread.

// Introduce Threadimport java. lang. thread;/*** create your own Thread to implement the run method (put the content you want to execute) */class MyThread extends Thread {/*** overwrite the run method of the super-class Thread */public void run () {for (int I = 0; I <10; I ++) {System. out. println ("+" + I + "") ;}} class ThreadDemo1 {public static void main (String [] args) {// create a custom thread, and start it new MyThread (). start () ;}}/* program output: 0th cycles, 1st cycles, 2nd cycles, 3rd cycles, 4th cycles, 5th cycles, 6th cycles, 7th cycles, 8th cycles */
Implementation Runnable

One implementedRunnableObject can beThreadObject execution,

Import java. lang. Thread; import java. lang. Runnable;/*** creates a class to implement the Runnable interface. */Class MyRunnable implements Runnable {/*** run method for implementing Runnable */public void run () {for (int I = 0; I <5; I ++) {System. out. println ("Runable: +" + I + "") ;}} class ThreadDemo2 {public static void main (String [] args) {// create a thread, create an object that has implemented Runnable // construct it, and then start this Thread new Thread (new MyRunnable ()). start () ;}}/* program output: Runable: 0th cycles Runable: 1st cycles Runable: 2nd cycles Runable: 3rd cycles */
synchronizedUse

Since it is multi-threaded, the problem of multi-threading will occur, such as simultaneously accessing the same resource to produce unexpected results, which we do not want to see. In Java, this problem can be easily solved.synchronizedLock the operation,synchronizedYou can lock objects or functions. The following is a comparison of unusedsynchronizedAnd usesynchronized.

Unused synchronizedStatus
import java.lang.Thread;import java.lang.Runnable;class MyRunnable implements Runnable {    private static int i=0;    public void run() {        for(; i<10; i++) {            try {                Thread.sleep(10);               } catch(Exception e) {            }            print(i);        }    }    private void print(int k) {        System.out.println(k);    }}class Demo {    public static void main(String[] args) {        MyRunnable r = new MyRunnable();        new Thread(r).start();        new Thread(r).start();    }}

The result is incorrect, because the two threads may enter the thread at the same time and print two identical values.

002345678910
Used synchronizedLater
import java.lang.Thread;import java.lang.Runnable;class MyRunnable implements Runnable {    private static int i=0;    public void run() {        synchronized(this) {            for(; i<10; i++) {                try {                    Thread.sleep(10);                   } catch(Exception e) {                }                print(i);            }        }    }    private void print(int k) {        System.out.println(k);    }}class Demo {    public static void main(String[] args) {        MyRunnable r = new MyRunnable();        new Thread(r).start();        new Thread(r).start();    }}

WhenforAfter the lock processing, the two threads will not enter the loop at the same time, so that the printed numbers will not go wrong.

0123456789

synchronizedThe lock object will have a flag (0/1). The default value is 0. When the thread runssynchronizedIf the flag of the object is 0, set it to 1; otherwise, wait. This flag can be called a "flag lock ". In this way, thread synchronization can be implemented.
AlthoughsynchronizedThis solution solves the security problem of multithreading, but it also has some drawbacks. It will reduce the execution efficiency of the program. Therefore,synchronizedIt cannot be placed at will. Try to place it in a required location. For example, an example of Singleton mode:

public class Single {    private Single mInstance;    private Single(){    }    public static Single getInstance() {        if(mInstance == null) {            synchronized(Single.class) {                if(mInstance == null) {                    mInstance = new Single();                }            }        }        return mInstance;    }}

HeresynchronizedCan be addedgetInstance()But this will greatly reduce the execution efficiency and remove the outerif(mInstance == null)But this will also add unnecessary judgment, thinking that ifmInstanceYou do not need to lock it after it is created. For this reason, the above method is the best. The inmostifTo judge whether it is necessary to explain, we can assume that both threads are executed to the firstifIf there is noifIf you judge,mInstanceWill be created twice, soifIs indispensable.

waitAnd notifyUse

waitAndnotifyIs the two methods in the Object, which is used for multi-thread control. If you want to use two threads to print outOddAndEvenThe specific code is as follows:

import java.lang.Thread;import java.lang.Runnable;class Temp {    public static boolean flag = false;}class Odd implements Runnable{    public void run() {        while(true) {            if(Temp.flag) {                try {                    wait();                } catch(Exception e) {}            }            System.out.println("Odd");            Temp.flag = !Temp.flag;            try {                notify();            } catch(Exception e) {}        }    }}class Even implements Runnable {    public void run() {        while(true) {            if(!Temp.flag) {                try {                    wait();                } catch(Exception e) {}            }            System.out.println("Even");            Temp.flag = !Temp.flag;            try {                notify();            } catch(Exception e) {}        }    }}class Demo {    public static void main(String[] args) {        new Thread(new Odd()).start();        new Thread(new Even()).start();    }}

Of course, apart fromnotifyMethod, andnotifyAllMethod used to wake up all threads.

Use of Lock

After JDK1.5, that is, after Java5.0, many new contents are added, such as some classes used for thread control,LockIs equivalentsynchronized,LockMediumlock()Andunlock()Used for locking and unlocking respectively. The general usage is as follows:

import java.lang.Runnable;import java.lang.Thread;import java.util.concurrent.locks.*;class Locks implements Runnable {    private Lock lock = new ReentrantLock();    private int index = 0;    public void run() {        while(true) {            lock.lock();            System.out.print(index + " ");            try {                Thread.sleep(100);            } catch(Exception e) {}            index ++;            lock.unlock();        }    }}class Demo {    public static void main(String[] args) {        Locks locks = new Locks();        new Thread(locks).start();        new Thread(locks).start();        new Thread(locks).start();    }}

In this way, the output can be printed sequentially.0 1 2 3 4 ···.
PassLockYou can create a Condition object, as shown in figure
Condition condition = lock.newCondition();
Then you can usecondition.await();Andcondition.signal()To pause and wake up threads, of course, there arecondition.signalAll()To wake up all threads.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.