Java Thread-Safe counter __java

Source: Internet
Author: User
Tags thread class visibility volatile
    One, multithreading and thread safety           java thread safety is the control of multiple threads accessing or modifying a resource in an orderly manner. This involves two important concepts: the Java memory model and the Java thread synchronization mechanism.       1.java memory model to solve two main problems: visibility and ordered visibility:  multiple threads cannot communicate with each other, communication between them can only be done through the shared variables       2. Thread synchronization         Because multiple threads in the same process share the memory space, in Java, a shared instance, when multiple threads try to modify the contents of an instance at the same time, the thread must implement a shared mutex, Synchronize multithreading.         The simplest synchronization is to mark a method as synchronized, and for the same instance, only one synchronized method can be executed at any one time. When a method is executing a synchronized method, the other thread, if it wants to execute any of the synchronized methods of this instance, must wait for the thread that currently executes the Synchronized method to exit this method before executing it sequentially.         However, non-synchronized methods are not affected, and synchronized methods can be executed concurrently by multiple threads, regardless of whether the synchronized method is currently being executed.        synchronized and Volatile keywords difference:         (1) The Synchronized keyword guarantees that multiple threads are mutually exclusive to the synchronization block, synchronized as a means of synchronization to solve the execution order and memory visibility of Java multithreading, while volatile keyword only solves the problem of multithread memory visibility;         (2) volatile keyword is a synchronous method provided by Java, but it is lightweight. Volatile can only guarantee the memory visibility of multithreading, can not guarantee the execution of multithreading. The most thorough synchronization is to ensure order and visibility, such as synchronized.         Any variables that are volatile modified are not copied to the working memory, and any changes are written in main memory in time. Therefore, for Valatile modified variables, all threads can immediately see, but volatile can not guarantee that the changes in the variable is orderly.       3. Basic Knowledge Java Multithreading implementation way: Inherit thread class, implement Runnable interface use which: http://www.cnblogs.com/rollenholt/archive/2011 /08/28/2156357.html better be the latter one. Second, instance code function: Write a thread-safe counter, 5 threads run at the same time, count to 1000, output thread name and count until 1000 code:
Import Java.util.concurrent.CountDownLatch;

Import Java.util.concurrent.atomic.AtomicInteger; /** * Features: Thread-safe counters, 5 threads running at the same time, counting to 1000, output thread name and Count * @author Yolanda * */public class Mysafethread implements runnable{pri vate static Atomicinteger count = new Atomicinteger (0);//thread-safe count variable private int threadcount = 0;//thread number Private St

     atic int num = 1;
               /** * Function: Count */public static void Calc () {while (Count.get ()) <1000) {  Count.incrementandget (),//1, returns the update value SYSTEM.OUT.PRINTLN ("Running is a thread" + thread.currentthread (). GetName () + ":" +         
          count);
          }/** * Feature: Thread Run method, only one thread per session access/public synchronized void Run () {(true)
               {try {thread.sleep (1);
               catch (Interruptedexception e) {e.printstacktrace ();
          } mysafethread.calc ();
     
 }
     }    public static void Main (string[] args) {//Create five thread instances and start for (int i = 1; i < 6; i++) {
               Thread mysafethread = new Thread (new Mysafethread ());
          Mysafethread.start ();
 }
     }     
}




Results:

Running is a thread thread-1:2

Running is a thread thread-4:4

Running is a thread thread-0:4

Running is a thread thread-3:2

Running is a thread thread-3:9

Running is a thread thread-3:10

Running is a thread thread-0:8

Running is a thread thread-4:7

Running is a thread thread-4:13

Running is a thread thread-4:14

Running is a thread thread-4:15

Running is a thread thread-4:16

Running is a thread thread-4:17

Running is a thread thread-4:18

Running is a thread thread-4:19

Running is thread thread-4:20 ...

Running is a thread thread-4:988

Running is a thread thread-4:989

Running is a thread thread-4:990

Running is a thread thread-4:991

Running is a thread thread-4:992

Running is a thread thread-4:993

Running is a thread thread-4:994

Running is a thread thread-4:995

Running is a thread thread-4:996

Running is a thread thread-4:997

Running is a thread thread-4:998

Running is a thread thread-4:999

Running is a thread thread-4:1000

Running is a thread thread-2:399

Running is a thread thread-1:398

Running is a thread thread-0:700

Running is a thread thread-3:402

=========================== I'm the update line ==============================

Look at the result of the above is actually a bit wrong, the previous count has been repeated, this is due to the location of the lock incorrectly caused. So rewrite the program for a bit.

Package com.yolanda.fun.thread;


Import Java.util.concurrent.atomic.AtomicInteger;


public class MySafeCalcThread1 implements Runnable {
	
	private static Atomicinteger count = new Atomicinteger (0);
	
    Public synchronized static void Calc () {
    	if (Count.get ()) < 1000) {
    		int c = Count.incrementandget ();//self 1, return more The new value
    		System.out.println ("Running is a thread" + thread.currentthread (). GetName () + ":" + C)
    	;
			
	}
	
	public void Run () {while
		 (true)
         {
			 mysafecalcthread1.calc ();
			 try {
				 thread.sleep (0);
			 } catch (Interruptedexception e) {
				 //TODO auto-generated catch
				 block E.printstacktrace ();


	}} public static void Main (string[] args) {for
		(int i = 0; i < 6; i++) {
			MySafeCalcThread1 thread = new MYSAFEC AlcThread1 ();
			Thread t = new thread (thread);
			T.start ();}}





Then the result is right, there is no repetition of the problem of counting.


Results:

Running is a thread thread-0:1
Running is a thread thread-1:2
Running is a thread thread-0:4
Running is a thread thread-2:3
Running is a thread thread-2:7
Running is a thread thread-0:6
Running is a thread thread-0:9
Running is a thread thread-1:5
Running is a thread thread-0:12
Running is a thread thread-5:11
Running is a thread thread-3:10
Running is a thread thread-2:8

.......

Running is a thread thread-4:996
Running is a thread thread-4:997
Running is a thread thread-4:998
Running is a thread thread-4:999
Running is a thread thread-4:1000
Running is a thread thread-1:743
Running is a thread thread-3:742
Running is a thread thread-0:935
Running is a thread thread-5:884
Running is a thread thread-2:747


There is another way to do it.

Package com.yolanda.fun.thread;


Import Java.util.concurrent.atomic.AtomicInteger;


public class MySafeCalcThread2 implements Runnable {
	
	private static Atomicinteger count = new Atomicinteger (0);
	
	public static void Calc () {While
		
		(Count.get ()) < 1000) {
			int c = 0;
			Synchronized (count) {
				if (Count.get ()) < 1000) {
					c = count.incrementandget ();//self 1, return update value
				}
			}
			System.out.println ("Running is a thread" + thread.currentthread (). GetName () + ":" + C);
		}
	
	public void Run () {while
		 (true)
         {
			 mysafecalcthread2.calc ();
			 try {
				 thread.sleep (0);
			 } catch (Interruptedexception e) {
				 //TODO auto-generated catch
				 block E.printstacktrace ();


	}} public static void Main (string[] args) {for
		(int i = 0; i < 6; i++) {
			MySafeCalcThread2 thread = new MYSAFEC AlcThread2 ();
			Thread t = new thread (thread);
			T.start ();}}








Results:

Running is a thread thread-0:1
Running is a thread thread-3:2
Running is a thread thread-4:3
Running is a thread thread-5:4
Running is a thread thread-0:5
Running is a thread thread-0:6
Running is a thread thread-2:7
Running is a thread thread-2:8
Running is a thread thread-1:9
Running is a thread thread-2:10

........

Running is a thread thread-2:990
Running is a thread thread-2:991
Running is a thread thread-2:992
Running is a thread thread-1:993
Running is a thread thread-2:994
Running is a thread thread-0:995
Running is a thread thread-5:996
Running is a thread thread-5:997
Running is a thread thread-5:998
Running is a thread thread-5:999
Running is a thread thread-5:1000


============================ I'm the update line ===============================

Here's a couple of ways to add Java multithreaded implementations

The first: inherit the thread class

Package com.yolanda.fun.thread;

public class Mythread extends Thread {public
	
	void run () {for
		(int i = 0; i < i++) {
			System.out.printl N ("thread" + thread.currentthread (). GetName () + "Running");
		}

	public static void Main (string[] args) {
		mythread thread = new Mythread ();
		Thread.Start ();
		
		for (int i = 0; i < i++) {
			System.out.println ("thread" + thread.currentthread (). GetName () + "Running");/thread main
		}

	}

}



Results:

Thread Main is running
Thread Thread-0 is running
Thread Main is running
Thread Main is running
Thread Thread-0 is running
Thread Thread-0 is running
Thread Main is running
Thread Thread-0 is running
Thread Main is running
Thread Thread-0 is running
Thread Thread-0 is running
Thread Thread-0 is running
Thread Thread-0 is running
Thread Thread-0 is running
Thread Thread-0 is running
Thread Main is running
Thread Main is running
Thread Main is running
Thread Main is running
Thread Main is running


Result Analysis: Here you can see the main thread and the Thread-0 thread running alternately.

So-called multithreading, which means that two-thread code can run at the same time without having to wait for the code in another thread to execute before it can run. For a single core CPU, there is no real multithreading, at each point in time, the CPU will execute specific code, because the CPU executes the code time quickly, so two threads of code alternate execution looks like the same execution. That specific execution of a piece of code how much time, and time-sharing mechanism system. Time-Sharing CPU time into a number of time slices, the operating system in time slices per unit of each thread of the code, the better the CPU time slice smaller. So can not see the obvious effect is also very normal, a thread printing 5 words would have been very soon, may be in the time slice of the execution completed. So the easiest solution is to turn the value of the For loop up a little bit (or you can add the Thread.Sleep method to the for loop).


The second type: implement Runnable interface . and inherited from the thread class, but after the implementation of runnable, or through a thread to start


Package com.yolanda.fun.thread;

public class Myrunnable implements runnable{public

	void Run () {for
		(int i = 0; i < i++) {
			System.out. println ("Thread" + thread.currentthread (). GetName () + "Running");
		}
	
	public static void Main (string[] args) {
		myrunnable thread = new myrunnable ();
		Thread t = new thread (thread);
		T.start ();
		
		for (int i = 0; i < i++) {
			System.out.println ("thread" + thread.currentthread (). GetName () + "Running");
		}

}


Results:

Thread Main is running
Thread Thread-0 is running
Thread Main is running
Thread Thread-0 is running
Thread Main is running
Thread Thread-0 is running
Thread Main is running
Thread Main is running
Thread Main is running
Thread Main is running
Thread Main is running
Thread Main is running
Thread Main is running
Thread Thread-0 is running
Thread Thread-0 is running
Thread Thread-0 is running
Thread Thread-0 is running
Thread Thread-0 is running
Thread Thread-0 is running
Thread Thread-0 is running


Two threads also run alternately.


In fact, the thread class is also the implementation of the Runnable interface.


The key to the contrast between the two implementations is the contrast between extends and implements, of course the latter is good. Because the first, inheritance can only but inherit, implementation may be more implementation, second, the way to achieve the comparison of inheritance, but also conducive to reducing the coupling between programs.

Therefore, the implementation of multithreading is almost always the way to use the Runnable interface.


Thread State

There are six types of thread states in the virtual machine, defined in Thread.state:


1, new status new
The state of the thread that was new but not started. For example, "thread t = new thread ()", T is a thread in the new state

2, can run the state runnable
New thread, calling the start () method is in the runnable state. A thread in the runnable state may be running in the Java Virtual machine, or it may be waiting for the processor's resources, because a thread must obtain the CPU's resources before it can run the contents of its run () method, or wait in line

3. Blocking blocked
If a thread is waiting for a monitor lock to enter a synchronized block/method, then the state of the threads is blocked blocked

4, Waiting for waiting
A thread is waiting waiting state because it calls the wait () method with the object without timeout, the join () method without the timeout thread, and the Locksupport Park () method.

5, timeout waiting for timed_waiting
A thread is due to a wait () method that invokes an object with a specified waiting time, a thread join () method, a thread's sleep () method, a Locksupport Parknanos () method, Locksupport Parkuntil () method, it will be in timeout waiting timed_waiting state

6, terminate the state terminated
When the thread call terminates or the run () method finishes executing, the thread is signaled. A thread in the signaled state does not have the ability to continue running.

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.