Java thread safety is not thread-safe

Source: Internet
Author: User

Often see some of the classes, some say thread safety, and some say thread is not safe, immediately confused force.

Thread security is not secure, mainly in the case of multi-threaded execution, if the program is caused by the thread to preempt resources between the bug is thread is not safe, take ArrayList and vector to give an example:

The ArrayList here are thread insecure, vector is thread-safe

Package Thread;import Java.util.list;import Java.util.concurrent.countdownlatch;public class MyThread  Implements Runnable{private list<object> list;private countdownlatch countdownlatch;public MyThread () {}public  MyThread (list<object> list,countdownlatch countdownlatch) {this.list=list;this.countdownlatch= Countdownlatch;} @Overridepublic void Run () {//Add 10 elements for each thread for (int i=0;i<10;i++) {List.add (New Object ());} Complete a Child thread Countdownlatch.countdown ();}}

  

Package Thread;import Java.util.arraylist;import Java.util.list;import java.util.vector;import Java.util.concurrent.countdownlatch;public class ThreadTest {/** * here to compare ArrayList and vectors to test * ArrayList is thread insecure * Vect  the or thread-safe *  */public static void Test () {///used to test the list collection list<object> list= new arraylist<object> ();// list<object> list = new vector<object> ()///number of threads int threadcount =10000;//used to keep the main thread waiting for thread to execute Countdownlatch  count=new Countdownlatch (ThreadCount); for (int i=0;i<threadcount;i++) {thread thread=new thread (new MyThread ( List, count)); Thread.Start ();} try {//main thread all execution completes, then execution down count.await ();} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println (List.size ());} public static void Main (string[] args) {for (int i=0;i<10;i++) {test ();}}}

Run structure:

99995
99998
99989
99973
99894
99970
99974
99977
99990
99989

When using vectors, change the set of tests

Package Thread;import Java.util.arraylist;import Java.util.list;import java.util.vector;import Java.util.concurrent.countdownlatch;public class ThreadTest {/** * here to compare ArrayList and vectors to test * ArrayList is thread insecure * Vect  the or thread-safe *  */public static void Test () {//used to test the List collection//list<object> list= new arraylist<object> (); list<object> list = new vector<object> ()///number of threads int threadcount =10000;//used to keep the main thread waiting for thread to execute Countdownlatch  count=new Countdownlatch (ThreadCount); for (int i=0;i<threadcount;i++) {thread thread=new thread (new MyThread ( List, count)); Thread.Start ();} try {//main thread all execution completes, then execution down count.await ();} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println (List.size ());} public static void Main (string[] args) {for (int i=0;i<10;i++) {test ();}}}

The result of this operation:

100000
100000
100000
100000
100000
100000
100000
100000
100000
100000

It's clear that using vectors this class is running correctly, which is called thread safety

Of course, this is just the code level, in fact, multithreading is not secure, mainly because of the CPU allocation mechanism, who gets the CPU who can execute, thus causing the thread of insecurity.

We can use the Synchronized keyword to synchronize blocks of code to achieve thread safety:

Here is an example of a synchronized synchronization:

Package Thread1;public class Bank {private int sum = 0;public void Add (int n) {sum = sum + N; System.out.println ("sum=" + Sum);}} Package Thread1;public class Cus implements Runnable {Bank b = new Bank (), @Overridepublic Void Run () {for (int i = 0; I &l T 3; i++) {b.add (100);}}} Package Thread1;public class Test {public static void main (string[] args) {Cus c = new Cus (), for (int i = 0; i < 3; i++ {New Thread (c). Start ();}}}

When you do not use the synchronized modifier, the run structure is:

sum= 100
Sum= 400
Sum= 500
sum= 300
Sum= 200
Sum= 600
Sum= 800
sum= 700
Sum= 900

Of course synchronized must be decorated in a code block that runs on the thread:

Package Thread1;public class Bank {private int sum = 0;public void Add (int n) {sum = sum + N; System.out.println ("sum=" + Sum);}} Package Thread1;public class Cus implements Runnable {Bank b = new Bank (), @Overridepublic Void Run () {synchronized (this) {F or (int i = 0; i < 3; i++) {b.add (100);}}} Package Thread1;public class Test {public    static void Main (String [] args) {        Cus c = new Cus ();        for (int i=0;i<3;i++) {        new Thread (c). Start ();}}    }

This guarantees that only one thread is running at a time, and the result is:

sum= 100
Sum= 200
sum= 300
Sum= 400
Sum= 500
Sum= 600
sum= 700
Sum= 800
Sum= 900

Ok,over

Make a little progress every day, keep on going

Java thread safety is not thread-safe

Related Article

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.