First review what threads and processes are. When the application is loaded into memory and ready to run, we say that a process was created. A process is a program with independent functionality about the last run activity of a data collection, a process that is an independent unit of system resource allocation and scheduling.
The thread is an entity of the process, is the basic unit of CPU dispatch and dispatch, and is the basic unit of the smaller process which can run independently. Threads do not have their own system resources, and multiple threads of a process share operating systems to allocate resources for each process.
One thread and one creation and revocation of another thread can be executed concurrently between multiple threads in the same process. A running program has at least one process, and a process has at least one thread. Logically, the meaning of multithreading is that multiple execution parts in an application can be executed concurrently. However, the system does not consider multiple threads as separate applications to allocate resources, and the basic unit of system resource allocation and dispatch is a thread. This is the important difference between processes and threads.
Thread state
In the operating system, threads typically have four states: Wait, blocked, running, and dead. The OS maintains the thread as a queue, the newly established thread is added to the end of the queue, and the thread is fetched from the head of the queue, and the thread is returned to the end of the queue after the CPU time slice of the thread has ended.
Daemon Threads and non-daemon threads
There are two types of threads in Java: 1, daemon thread, 2, non-daemon (user) thread. The difference is that the daemon thread created by the parent thread ends at the end of the parent thread, and the non-daemon thread created by the parent thread will continue to survive at the end of the parent thread. And for the process, as long as the thread is alive, the process is still alive.
Each Java application will have at least one non-daemon thread, the main thread. The main thread dies when the user closes the application. However, if the program creates other non-daemon threads, the main process will continue to survive.
Creating Threads
In the Java program to create a thread, can be implemented in the following ways: 1, implements Runnable interface, 2, extends thread class, 3, through the Threadgroup class implementation.
Class Threada implements runnable{... @Override public Void Run () { ... }} Class Threadb extends thread{... . @Override public Void Run () { ... }} public class threadsample{public static void Main (string[] args) { thread Samplea = new Thread (new Threada ()); C13/>samplea.start (); Thread Sampleb = new threadb (); Sampleb.start (); }}
These are the two most common ways to create threads, and in the run () method you can write transactions that you want the thread to complete. Implementing the Runnable interface is preferable to inheriting the thread class method.
At this point we have only created one thread, not multithreading.
Basic operation of the thread
- Setting the Deamon/non-deamon Property
- Start/Stop Thread
- Suspend/Resume thread (by calling the Stop method, the thread may stop, the call to the Supend method may suspend the thread, and another running program can resume the suspended thread by calling the Resume method.) But these methods were abandoned at the beginning of the J2SE because it was easy to create deadlocks. )
- Concession operation
- Yield method
- Waits for other objects (called the Obj.wait () method for other running threads, the thread may be waiting for notification of an object. Obj only wants to be the waiting object for the front thread. )
- Interrupt/Disturb Thread (three methods: Interrupt, isinterrupted, and interrupted.)
Thread synchronization
These are just some of the basics of creating threads and threads and do not involve multithreading. If there are two baskets, two very boring people do the opposite thing, one moves the ball from the left pile to the right, and the other is opposite. Under normal circumstances, the total number of two-box balls should be constant after the two players have had enough. To impersonate a person with a thread, the program is as follows:
public class bucketballgame{private int bucket[] = {10000, 10000}; private static Boolean right_to_left; public static void Main (string[] args) {new Bucketballgame (). Dotransfers (); } private void Dotransfers () {for (int i=0; i <; i++) {New Thread (new Transferthread (! Right_to_left). Start (); New Thread (New Transferthread (Right_to_left)). Start (); }} public void Transfer (Boolean direction, int numtotransfer) {if (direction = = Right_to_left) {BU Cket[0] + = Numtotransfer; BUCKET[1]-= Numtotransfer; }else{bucket[0]-= Numtotransfer; BUCKET[1] + = Numtotransfer; } System.out.println ("Bucket_right:" +bucket[0]+ "Bucket_left:" +bucket[1]+ "total:" + (bucket[0]+bucket[1])); } Private class Transferthread implements runnable{private Boolean direction; Public Transferthread (Boolean direction) {this.direction = direction; } @Override public void Run () {for (int i=0; i <; i++) {Transfer (direction, (int) (Math.random () *2000)); try{thread.sleep ((int) (Math.random () *100)); }catch (Interruptedexception ex) {}}}}
But the sum of the results of the run is not constant 20000, because my dream did not take the atomic unit to move out or join the ball operation. The workaround is to add a sync keyword to the move ball, as follows:
Public synchronized void Transfer (Boolean direction, int numtotransfer) {
Java provides a special waiting/notification mechanism, taking producer/consumer issues as an example:
public class producerconsumergame{public static void Main (String args[]) {Bucket bucket = new bucket (); New Thread (New Producer (bucket)). Start (); New Thread (New Consumer (bucket)). Start (); }}final class Consumer implements runnable{private bucket bucket; Public Consumer (Bucket bucket) {this.bucket = bucket; } @Override public void Run () {for (int i=0; i <; i++) {bucket.get (); }}}final class Producer implements runnable{private bucket bucket; Public Producer (Bucket bucket) {this.bucket = bucket; } @Override public void Run () {for (int i=0; i <; i++) {bucket.put ((int) (Math.random () *100)); }}}class bucket{private int packofballs; Private Boolean available = false; public synchronized int get () {if (available = = false) {try{wait (); }catch (Interruptedexception e) {}} System. OUT.PRINTLN ("Consumer Got:" +packofballs); Available = false; Notify (); return packofballs; Public synchronized void put (int packofballs) {if (available) {try{wait (); }catch (Interruptedexception e) {}} this.packofballs = Packofballs; Available = true; System.out.println ("Producer put:" +packofballs); Notify (); }}
Producer/consumer models can be observed in real-life scenarios, such as chat programs.
When to synchronize
In multi-threading, it is common for multiple threads to operate on shared data, so synchronization is essential. Synchronized semantics guarantees that only one thread can access the protected section at any given time. But this often leads to performance problems. So while multithreaded programs need to be synchronized enough to protect shared data and avoid them from being compromised, don't overdo it, consider using the volatile keyword for synchronization.
On Java threading