Java implements multithreading in two ways: inheriting the thread class or implementing runnable. The start () method is invoked when the thread starts.
Implementing the Runnable interface enables resource sharing
Let's take a look at the code here:
public class Thread1 extends thread{private int num = 5;
@Override public void Run () {for (int i=0;i<10;i++) {if (this.num>0) {
System.out.println ("Remaining ticket 1:" +num--);
"}}} public class Thread2 implements runnable{private int num = 5; public void Run () {for (int i=0;i<10;i++) {if (this.num>0) {SYSTEM.OUT.P
Rintln ("Remaining ticket 2:" +num--); /** * @author Shu Yuwei * @time 2015-4-9 pm 09:37:56 * @param args/public s
tatic void Main (string[] args) {Thread1 T1 = new Thread1 ();
T1.setname ("Ticket window 1");
Thread1 t2 = new Thread1 ();
T1.setname ("Ticket window 2");
Thread1 t3 = new Thread1 ();
T1.setname ("Ticket window 3");
T1.start ();
T2.start ();
T3.start ();
Thread2 t1_ = new Thread2 ();
Thread t1_1 = new Thread (t1_); T1_1.setname ("Ticket window 1_");
Thread t2_2 = new Thread (t1_);
T2_2.setname ("Ticket window 2_");
Thread t3_3 = new Thread (t1_);
T1_1.setname ("Ticket window 3_");
T1_1.start ();
T2_2.start ();
T3_3.start (); }
}
The
results are as follows:
A total of 5 tickets, thread 1 sold 15 times, obviously the resources are not shared, and thread 2 only bought 5 times.
How Java Multithreading accesses shared resources:
1, if each thread executes the same code, you can use the same Runnable object, which has that shared data (ticket system)
2, if each thread executes a different code, At this time, different runnable objects are needed, and there are two ways to realize the data sharing between these runnable.
(1), encapsulates the shared data in another object, and then passes the object to each Runnable object. The way each thread operates on shared data is also assigned to that object, which makes it easy to implement mutexes and communications for each operation on that data.
(2), these runnable objects as internal classes in a class, shared data as member variables in this external class, and each thread's method of manipulating shared data is also assigned to an external class in order to achieve mutual exclusion and communication for each operation of the shared data. These methods of calling external classes as individual runnable objects of the inner class.
(3), combination of the above two ways: the shared data is encapsulated in another object, and each thread's method of manipulating the shared data is assigned to that object as a member variable or a local variable in the method in the external class. The Runnable object for each thread acts as the inner class or local inner class of the member inside the outer class.
(4), in short, several pieces of code to synchronize mutexes are best placed in separate methods, which are placed in the same class, which makes it easier to achieve synchronization mutexes and communication between them.
3, an extreme and simple way to define a static variable in any class that is shared by all threads
because of the uncertainty of its operation in a thread operation, it provides a way to obtain the current operation thread:
public static thread CurrentThread ();
Description:
The name of a thread is typically set before it is started, it is best not to set the same name, preferably not to change the name of a thread.
A Java program starts at least 2 threads in Java execution: a main thread and a garbage collection thread.
Multithreading Synchronization Issues
If you use the Runnable method to implement the ticket system, in the event of a delay in buying tickets, such as:
public class Thread2 implements runnable{
private int num = 5;
public void Run () {for
(int i=0;i<10;i++)
{
try {
thread.sleep);
} catch ( Interruptedexception e) {
e.printstacktrace ();
}
if (this.num>0) {
System.out.println ("Remaining ticket 2:" +num--);}}}
The output results are as follows:
If you solve such a problem, you must use synchronization, that is, there is only one thread in the same time period.
Java multithreading with this method step relies mainly on several methods and keywords
1. Wait method
Method of object that causes the thread that is currently calling the part of the wait method to stop executing and releases the lock of the code block that is currently obtained to invoke wait, and reverts to the competitive lock state when other threads call the Notify or Notifyall method
Wait must be called in a code block that has a lock (synchronized decoration)
When you resume execution, you start with the next statement in wait, because the waiting method should always be invoked in the while loop to avoid conditions that resume execution after resuming execution and that do not meet the criteria for continuing.
If there is time in the wait method parameter, the thread will also activate to the competitive state after the notify and Notifyall are invoked to activate the thread that is in the wait state to enter the lock competition, interrupt it in another thread, or when the parameter time is up.
A thread that is invoked by the wait method must obtain a lock that was released prior to execution to wait before resuming execution.
2, notify method and Notifyall method
The Notify method is not executed immediately by invoking the wait method, but not activating a thread scheduling queue (that is, entering a competitive lock). and specifically which thread is not guaranteed. The other point is that the awakened thread must be the lock that waits for the release of the wait.
The Notifyall method wakes all calls to the wait method, and processes that have not yet been activated enter the competition queue.
3, synchronized key word
Used to identify a common method, it means that a thread must take the lock on the object that the method is executing in order to execute the method.
When used to identify a static method, it means that a thread must obtain the class lock of the class in which the method is being executed.
Modifies a code block. A code block like synchronized (OBJ) {} that represents a thread to execute must obtain a lock on object, which is intended to reduce the granularity of the lock and ensure that the entire object is not locked when the locks required for different blocks are not conflicting. Using 0-Length byte array objects to make obj is very economical.
4. Atomic Action Atomic operation
In Java, the following are atomic operations, but in C and C + + are not
Read and write to reference variables and original data type variables except long and double
Read and write to all variables declared as volatile (including long and double)
In addition, some thread-safe classes and methods that are not dependent on synchronization mechanisms are provided in the Java.util.concurrent and java.util.concurrent.atomic packages.
The following uses synchronized to resolve synchronization issues:
1. Sync code block
public class Thread2 implements runnable{
private int num = 5;
public void Run () {for
(int i=0;i<10;i++)
{
//Use synchronous code block
synchronized (this) {
try {
Thread.Sleep (+);
} catch (Interruptedexception e) {
e.printstacktrace ();
}
}
if (this.num>0) {
System.out.println ("Remaining ticket 2:" +num--);}}}
2. Synchronous method
public class Thread3 implements runnable{private int num = 5;
public void Run () {for (int i=0;i<10;i++) {sale (); }///Using the Sync method public synchronized void sale () {try {thread.sleep (300);
Rest 300 milliseconds} catch (Interruptedexception e) {e.printstacktrace ();
} if (num > 0) {System.out.println (Thread.CurrentThread (). GetName () + "buy tickets" +this.num--);
} public static void Main (string[] args) {Thread3 t3 = new Thread3 ();
New Thread (T3, "ticket window 1"). Start ();
New Thread (T3, "Ticket window 2"). Start ();
New Thread (T3, "ticket window 3"). Start (); }
}
Resource sharing between multithreading requires synchronization, but too much synchronization can cause deadlocks. A
deadlock is in a multiple-program system in which each process in a group of processes waits indefinitely for another thread, thus possessing resources that will never be released.
The cause of the deadlock:
1, competitive resources, the system provides limited resources, can not meet the requirements of each process
2, multiple programs run, the process to advance the order is unreasonable
Create deadlock requirements:
1, mutual-exclusion resources use
2, occupy and wait for resource
3, do not Rob resources
4, cycle waiting for resources
to http://www.cnblogs.com/dennisit/archive/2013/02/24/2925288.html