Read in Java reading notes (ii) Multithreading __java

Source: Internet
Author: User
Tags idn mutex rand thread class throw exception

First, the basic concept of multithreading
Exclusive: Maintains state consistency by blocking harmful interference between multiple concurrent behaviors. Asynchronous methods are usually used sychronized
State dependency: Triggering, blocking, delaying, resuming, some behavior is caused by some object being in these behaviors may be successful or have been
The state of success is decided. Mainly through monitors (monitor) to achieve object.wait object.notify, Object.notifyall

Client Client:client Object expects execution of an action
Service Serverce: Include code to execute this action
Principal: Customers and services can be an object, and this object is a body. And the object he calls is usually a helper object (Help)

Synchronized: Prevents and causes inconsistent data, and can modify a method or block of code.
Each instance of a 1.Object or subclass is locked before entering the Synchronized method and automatically releases the lock when it leaves the method.
Using the Synchronized keyword to define a method locks all static or non-static methods defined using the Synchronzied keyword in the class
The Synchronized method of different object instances is not interfered with. That is, other threads can still access the Synchronized method in another object instance of the same class at the same time;
It can work on all object instances of a class for a method that modifies the static.
2. Lock is also the code block, just need to specify the lock on that object. Use classes. Class in a static block of code to indicate that
In a non-static block of code, most of this is used
The 3.synchronized keyword is not inheritable, that is, the base class method synchronized F () {} is not automatically synchronized F () {} in the inheriting class, but instead becomes F () {}. An inheriting class requires you to explicitly specify a method of its Synchronized method
Rules:
1 always just update the member variable of the object is locked
2 always only lock when accessing the member variable of the object that is likely to be updated
3 never lock the other object's methods when calling it


Second, Java.util.concurent package introduction
1, the executor (Executor) is used to manage the thread object, here are three kinds of Executor
(1) Newcachedthreadpool
Executorservice exec = Executors.newcachedthreadpool ();//Create a thread pool to create a new thread as needed
for (int = 0; i<5; i++) {
Exec.execute (new Liftoff ());//liftoff implements runnable interface classes
Exec.shutdown ()
}
(2) Newfixedthreadpool
Executorservice exec = Executors.newfixedthreadpool (5);//Create a thread pool that reuses the number of fixed threads to run these threads in a shared, unbounded queue.
for (int = 0; i<5; i++) {
Exec.execute (new Liftoff ());//liftoff implements runnable interface classes
Exec.shutdown ()
}
(3) Newsinglethreadpool
Singlethreadpool is like a fixedthreadpool with a thread count of 1, and if you submit multiple tasks to Singlethreadpool, the tasks will be sorted and each task ends before the next task starts.
Executorservice exec = Executors.newsinglethreadpool ();//Create a Executor that uses a single worker thread to run the thread in a unbounded queue.
for (int = 0; i<5; i++) {
Exec.execute (new Liftoff ());//liftoff implements runnable interface classes
Exec.shutdown ()
}

2. Generate the return value from the task
Runnable is a stand-alone task that performs work, but does not return any value, and if the callable interface is implemented, the callable interface method call () can return a value.
Package cn.com.cdl.chen;
/**
* @ Class Callabledemo.java
* @ Description
* @ Company OpenData
* @ Author chenlly e-mail:chenlly99@gmail.com
* @ Version 1.0
* Date Mar 13, 2010
*/
Import java.util.ArrayList;
Import java.util.concurrent.Callable;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Future;
public class callabledemo{
public static void Main (string[] args) {

Executorservice exec = Executors.newcachedthreadpool ();
arraylist<future<string>> results = new arraylist<future<string>> ();
for (int i = 0; i < i++) {
Results.add (Exec.submit (New Taskwithresult (i)); The Submit method is used here to produce the future object
}

for (future<string> fs:results) {
try{
if (Fs.isdone ()) {//Check whether the future is finished or not isdone (), the Get () will block until the result is ready.
System.out.println (Fs.get ());//Gets the value returned by the call () method via get ().
}
catch (Exception ex) {
Ex.printstacktrace ();
} finally{
Exec.shutdown ();
}
}
}
}
Class Taskwithresult implements callable<string>{
private int id;

public taskwithresult (int id) {
This.id = ID;
}

Public String call () {
Return ' result of Taskwithresult ' + ID;
}


}
Results:
Result of TaskWithResult0
Result of TASKWITHRESULT1
Result of TASKWITHRESULT2
Result of TASKWITHRESULT3
Result of TASKWITHRESULT4
Result of TASKWITHRESULT5
Result of TASKWITHRESULT6
Result of TaskWithResult7
Result of TASKWITHRESULT8
Result of TaskWithResult9
difference between sleep () and wait () methods
Sleep is a static method of the thread class. The function of sleep is to allow the thread to hibernate for the time it is set, to recover when the time arrives, that is to say, sleeping will be at the time of arrival to the event recovery thread execution, whose control range is by the current thread block
Wait is the method of object, that is, you can call the Wait method on any object, and invoking the Wait method will suspend the caller's thread until the other thread calls the Notify method of the same object to reactivate the caller
Sleep () is for a thread to pause for a period of time, and its control is determined by the current thread, that is, within a thread. Well, for example, the thing I'm going to do is "ignition-> boil water->", and when I finish the fire I don't boil the water immediately, I'll take a break for a while before I burn. The initiative for the operation is controlled by my process.
and wait (), first of all, this is called by a certain object to interpret this object as a messenger, when the person says "Pause!" inside a thread., is also thisobj.wait (), where the suspension is blocked, or "ignition-> boil water-> cooking", Thisobj is like a man who supervises me. Standing next to me, the thread should have executed 2 after 1, and then executed 3,
And at 2 I was stopped by that object, so I would have been waiting here and not performing 3, but the process was not over, and I was trying to cook, but not allowed until the object said somewhere, "notify paused thread to start!", that is, when thisobj.notify (), So I can cook, and the suspended thread will continue to execute from the pause.
The essential difference is the running state control of a thread, the problem of communication between threads.

3, T.join (); method
Package cn.com.cdl.chen;
/**
* @ Class Joining.java
* @ Description
* @ Company OpenData
* @ Author chenlly e-mail:chenlly99@gmail.com
* @ Version 1.0
* Date Mar 14, 2010
*/
Class Sleeper extends thread{

private int duration;

Public Sleeper (String name, int sleeptime) {
Super (name);
Duration = Sleeptime;
Start ();
}

public void Run () {
try{
Sleep (duration);
}catch (Interruptedexception ex) {
System.out.println (This.getname () + "was interrupted." + "isinterrupted ():" +this.isinterrupted ());
}

System.out.println (This.getname () + "has awakened");
}
}
Class Joiner extends thread{
Private sleeper sleeper;

Public Joiner (String name, sleeper sleeper) {
Super (name);
This.sleeper = sleeper;
Start ();
}

public void Run () {

try{
Sleeper.join ();//thread sleeper the join () on the thread joiner, the joiner thread is suspended until the sleeper thread ends (isAlive () ==false). only to recover
catch (Interruptedexception ex) {
System.out.print ("interrupted");
}

System.out.println (This.getname () + "join completed");
}
}

public class Joining {
public static void Main (String []args) {
Sleeper sleepy = new Sleeper ("Sleepy", 1500);
Sleeper grumpy = new Sleeper ("Grumpy", 1500);

Joiner dopey = new Joiner ("Dopey", sleepy);
Joiner doc = new Joiner ("Doc", grumpy);

Grumpy.interrupt ();//grumpy interrupted, Doc will continue
}
}

  out put:
  grumpy is interrupted.isinterrupted (): false//When a thread calls interrupt () on that thread, The thread will be given a flag, however, the exception will clean up the flag when it is caught, so calling interrupt () in the catch code block is always false
  grumpy has awakened
   Doc Join completed
  sleepy has awakened
  dopey join completed

4, display lock, java.util.concurrent.locks
public synchronized int Next () {
...
try{
Return
}catch () {

}
}
Private lock lock = new Reentrantlock ();
public int Next () {
try{
Lock.lock ();
...
Return
catch () {
Lock.unlock ();
}

Using the Synchronized keyword and display lock can resolve resource synchronization problems, and the Synchronized keyword is less than the amount of lock code displayed, but when the synchronized keyword does not
Can try to get the lock for a while and then give it up.

5. Thread Localization: java.lang.ThreadLocal
Its function is very simple, for each thread that uses this variable provides a copy of the variable value, each thread can independently change its own copy, and not with the other threads of the replica conflict. From a thread's point of view, it's as if every thread owns the variable completely
The object's contents are usually accessed through the Get (), set () method, and the Get () method returns a copy of the object associated with its line threads relative, while the set () method inserts the parameter value into the object stored for its thread.
Package cn.com.cdl.chen;
Import Java.util.Random;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.TimeUnit;
Class Accessor implements runnable{
private final int id;
public accessor (int idn) {id = IDN;}
public void Run () {
while (! Thread.CurrentThread (). isinterrupted ()) {
Threadlocalvariableholder.increment ();
System.out.println (this);
Thread.yield ();
}
}
Public String toString () {
Return "#" +id+ ":" +threadlocalvariableholder.get ();
}

}
public class threadlocalvariableholder{
private static threadlocal<integer> value=
New Threadlocal<integer> () {
Private Random rand = new Random (47);
Protected synchronized Integer InitialValue () {
Return Rand.nextint (10000);
}
};

public static void increment () {
Value.set (Value.get () + 1);
}

public static int Get () {return value.get ();}

public static void Main (String []args) throws exception{
Executorservice exec = Executors.newcachedthreadpool ();
for (int i = 0; i < 5; i++) {
Exec.execute (new accessor (i));
}
TimeUnit.SECONDS.sleep (3);
Exec.shutdownnow ();
}
}
Output
#2:35601
#4:30424
#0:37948
#2:35602
#4:30425
#0:37949
#2:35603
#4:30426
#0:37950

6, caught exception in the thread
The run () method of a task usually has some form of loop that keeps the task running until it is no longer needed, so set the conditions for jumping out of the loop.
Usually, it is written in the form of an infinite loop, which means that unless a condition is used to terminate it, it will run forever.
Because of the intrinsic nature of the thread, we cannot catch exceptions escaping from the thread, such as:

Package cn.com.chenlly;

public class ThreadException implements Runnable {

public void Run () {
throw new RuntimeException ("I ' m throw Exception");
}

public static void Main (String []args) {
try{
Thread t = new Thread (new ThreadException ());
T.start ();

catch (Exception ex) {
System.out.println ("Exception has been handled!");
Ex.printstacktrace ();
}
}

}

/* Output
Exception in Thread "Thread-0" Java.lang.runtimeexception:i ' m throw Exception
At Cn.com.chenlly.ThreadException.run (threadexception.java:6)
At Java.lang.Thread.run (Unknown Source)
That is, Tyr catch cannot catch an exception escaping from the Run method.
Thread.uncaughtexceptionhandler This interface is the interface that invokes the handler when Thread abruptly terminates because of an unhandled exception.
It allows you to attach an exception handler to each thread object.
Package cn.com.chenlly;

public class ThreadException implements Runnable {

public void Run () {
throw new RuntimeException ("I ' m throw Exception");
}

public static void Main (string[] args) {
Thread t = new Thread (new ThreadException ());
T.setuncaughtexceptionhandler (New Myuncaughtexception ());//Add an exception handler
T.start ();
}

}

Exception handler
Class Myuncaughtexception implements Thread.uncaughtexceptionhandler {
public void Uncaughtexception (Thread t, Throwable e) {
System.out.println (t + ":" + e.getmessage ());
}
}


/* Output
Thread[thread-0,5,main]: I ' m throw Exception


7. Assistance between Threads:
Multiple tasks, you can synchronize the behavior of two threads by using a lock or synchronized (mutex) method so that one task does not interfere with the resources of another task.
So how to make it possible for multiple tasks to work together to solve a problem. Use the same mutex base: mutex. Mutual exclusion ensures that only one task can respond to a signal.

Eg: one is to paint the wax on the car and one to polish it. The polishing task is not operable until the wax is finished, and the wax task must wait for the polishing to finish before applying another layer of wax.
The car object hangs and restarts these tasks through wait, and notifyall.
Package cn.com.chenlly;

Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.TimeUnit;

Class car{
Private Boolean Waxon = true;//defaults to polished state, sync signal

Wax finish, set state, and wake waxing
Public synchronized void waxed () {
Waxon = false;
Notifyall ();
}

Polished finish, set state, and wake waxing
Public synchronized void buffing () {
Waxon = true;
Notifyall ();
}

Whether polishing finish
Public synchronized void Waitforwaxed () throws interruptedexception{
while (!waxon) {
Wait ();
}
}

Whether waxing ends
Public synchronized void Waitforbuffing () throws interruptedexception{
while (Waxon) {
Wait ();
}
}

}

Waxing
Class Waxon implements runnable{
Private car car;
Public Waxon (car car) {
This.car = car;
}
public void Run () {
try{
while (! Thread.interrupted ()) {
Car.waitforwaxed ();
System.out.println ("Wax on!");
TimeUnit.SECONDS.sleep (2);
Car.waxed ();
}
catch (Exception ex) {
Ex.printstacktrace ();
}
}
}
Polishing
Class Buffing implements runnable{
Private car car;
Public buffing (car car) {
This.car = car;
}
public void Run () {
try{
while (! Thread.interrupted ()) {
Car.waitforbuffing ();
System.out.println ("buffing on!");
TimeUnit.SECONDS.sleep (2);
Car.buffing ();
}
catch (Exception ex) {
Ex.printstacktrace ();
}
}
}
public class Waxomatic {
public static void Main (String []args) {
try{
Car car = new car ();
Executorservice exec = Executors.newcachedthreadpool ();
Exec.execute (new Waxon (car));
Exec.execute (new buffing (car));
TimeUnit.SECONDS.sleep (10);
Exec.shutdownnow ();
catch (Interruptedexception ex) {
Ex.printstacktrace ();
}
}
}

/* Output
Wax on!
Buffing on!
Wax on!
Buffing on!
Wax on!
Buffing on!

Waxing and polishing are carried out successively, the two steps are repeatedly repeated when the control is passed between the two. The two tasks are interrupted after 5 seconds.


8, Thread deadlock problem

1. Deadlock: A task is waiting for another task, the latter is waiting for another task, so that the continuous cycle between tasks is a deadlock problem
Typical philosophers dining is a deadlock problem.

2. Four conditions of deadlock:
(1) Mutually exclusive conditions: resources cannot be shared and can only be used by one process.
(2) Request and retention conditions (Hold and wait): processes that have been given resources can request new resources again.
(3) Non-deprivation: allocated resources cannot be forcibly deprived of the corresponding process
(4) Cyclic waiting condition (circular wait): Several processes in the system form a loop in which each process waits for resources that are being occupied by adjacent processes.

3. Strategies for handling deadlocks
By breaking the deadlock four of the necessary conditions to prevent deadlock generation.

The question of dining philosophers: The question involves five philosophers who alternately think and dine.
They sit at a round table around the five chairs, the central table is a bowl of rice, the table has five chopsticks,
Placed in the middle of each of the two adjacent seats respectively.
When philosophers think, he does not talk to others. When the philosopher is hungry, he will pick up two chopsticks to dine with him,
But he was likely to get one, and the other side was in the hands of his neighbour.
Only when he got two chopsticks did he begin to eat. After completing the meal,
He put two chopsticks back in place, and then began to think again.

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.