Multithreaded processes: Each process is a separate code and data space (process context), there is a large overhead of switching between processes, and a process contains 1-n threads. (Process is the smallest unit of resource allocation) thread: is a logical flow running in a single process context that is dispatched by the kernel. The same class of threads share code and data space, each thread has a separate run stack and program counter (PC), and thread switching overhead is small. (Thread is the smallest unit of CPU scheduling)
Creating and starting a thread
Two ways to implement Multithreading: 1. Implementing the Runnable Interface (recommended) 2. Inherit thread
ImportJava.io.File;/*** Start a thread, scan a specified folder every second, find that there are other files in the deletion, to ensure that the folder can only exist (*.txt) files. * @authordong007 **/ Public classThreadtxtextendsThread {/**Specify folder path*/ Private StaticString PATH = ""; Public voidRun () {File file=NewFile (PATH); File[] Filearray=File.listfiles (); while(true) { Try{Thread.Sleep (1000);//Sleep One second}Catch(interruptedexception e) {e.printstacktrace (); } for(File currfile:filearray) {if(Currfile.isfile () &&! ((Currfile.getname ()). EndsWith (". txt")) {currfile.delete (); System.out.println ("A non-*.txt file is deleted under this folder"); } Else if(Currfile.isdirectory ()) {System.out.println ("File does not exist under this folder"); } Else{System.out.println (End); } } } }}View Code
ImportJava.io.File; Public classMonitorrunnerImplementsRunnable {Private StaticString PATH = ""; Public voidRun () {File file=NewFile (PATH); File[] Filearray=File.listfiles (); intBefore = 0; intCurrent = 0; while(true) { Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } before=Current ; Current=filearray.length; intCount = current-before; if(count = = 0) {System.out.println ("Nothing has been done"); } Else if(Count > 0) {System.out.println ("New File Action"); } Else{System.out.println ("Delete File Action"); } } }}View CodeThe run () method writes code that requires execution in the thread, Thread.CurrentThread (), creates an instance of thread in the main method, and invokes the. Start method of the thread instance in the constructor of the runnable instance.
Public class Main { publicstaticvoid main (string[] args) { new threadtxt (); Threadtxt.start (); New Monitorrunner (); New Thread (monitorrunner); Monitorthread.start (); }}
View Code
6 states of the thread:
You can return to the current state by calling the GetState () method of the current thread instance? New (newly created) thread T=new thread (r); ? Runnable (can run) T.start (); ? Blocked (blocked) when a thread attempts to acquire an internal object lock, and the lock is held by another thread, the thread goes into a blocking state. Waiting (wait) when a thread waits for another thread to notify the scheduler of a condition, it enters its own wait state. such as calling the Object.wait method or the Thread.Join method.? Timed Waiting (timed wait) there are several ways to have a timeout parameter. Calling them causes the thread to enter a timed wait state. This status will be maintained until the timeout expires or the appropriate notification is received. such as Thread.sleep,object.wait,thread.join? The Terminated (terminated) thread was terminated for one of the following two reasons: 1. Natural death due to the normal exit of the Run method; 2. Accidental death due to an uncaught exception terminating the Run method
In some books and posts, the thread is run in five stages: Create, ready, run, block, terminate. 1. New state: A new Thread object was created. 2. Ready state (Runnable): After the thread object is created, other threads call the object's start () method. The state of the thread is located in a pool of running threads that becomes operational and waits for the CPU to be used. 3, running State (Running): The ready state of the thread gets the CPU, executes the program code. 4, blocking State (Blocked): Blocking state is the thread for some reason to abandon the use of the CPU, temporarily stop running. Until the thread is in a ready state, the opportunity to go to the running state is reached. There are three types of blocking: (i), waiting for blocking: The running thread executes the wait () method, and the JVM puts the thread into the waiting pool. (wait releases the held lock) (ii), synchronous blocking: When a running thread acquires a synchronization lock on an object, the JVM puts the thread into the lock pool if the synchronization lock is occupied by another thread. (iii), other blocking: The running thread executes the sleep () or join () method, or when an I/O request is made, the JVM will place the thread in a blocked state. When the sleep () state times out, join () waits for the thread to terminate or time out, or the I/O process finishes, the thread is re-entered in a ready state. (Note that sleep does not release held locks) 5, Dead State (Dead): The thread finishes executing or exits the run () method because of an exception, and the thread ends the life cycle.Scheduling of Threads1, adjust the thread priority: Java threads have priority, high priority threads will get more running opportunities. The priority of a Java thread is expressed in integers, and the value range is the 1~10,thread class has the following three static constants: the static int max_priority thread can have the highest priority, with a value of 10. The static int min_priority thread can have the lowest priority, with a value of 1. The static int norm_priority The default priority assigned to the thread, with a value of 5. The SetPriority () and GetPriority () methods of the thread class are used to set and get the priority of the thread, respectively. Each thread has a default priority. The default priority for the primary thread is thread.norm_priority. The priority of a thread has an inheritance relationship, such as the B thread created in a thread, then B will have the same priority as a. The JVM provides 10 thread priorities, but does not map well with common operating systems. If you want the program to be portable to each operating system, you should only use the thread class with the following three static constants as priority, which ensures that the same precedence is used for the same scheduling.  2, Thread sleep: thread.sleep (Long Millis) method, which causes the thread to go to the blocking state. The Millis parameter sets the time to sleep, in milliseconds. When sleep is over, it becomes ready (Runnable) state. Sleep () platform portability is good. 3. Thread waits: The Wait () method in the object class causes the current thread to wait until another thread calls the Notify () method of this object or the Notifyall () Wake method. This two wake-up method is also a method in the object class, and behaves equivalent to calling wait (0). 4. Thread Concession: The Thread.yield () method pauses the currently executing thread object and gives the execution opportunity to the same or higher priority thread. 5, Thread join: Join () method, wait for other threads to terminate. Invoking the Join () method of another thread in the current thread, the current thread goes into a blocking state until the other process finishes running, and the current thread is then turned into a ready state by blocking. 6. Thread Wakeup: The Notify () method in the object class that wakes up a single thread waiting on this objects monitor. If all threads are waiting on this object, then one of the threads is chosen to wake up. The choice is arbitrary and occurs when a decision is made on the implementation. The thread waits on the object's monitor by calling one of the wait methods. Until the current thread discards the lock on this object to continueExecutes the thread that was awakened. The awakened thread competes with all other threads that are actively synchronizing on the object, for example, the thread that wakes up does not have a reliable privilege or disadvantage as the next thread that locks the object. A similar approach also has a notifyall () that wakes up all the threads waiting on this object monitor. NOTE: Thread suspend () and resume () Two methods have been abolished in JDK1.5 and are no longer introduced. Because there is a deadlock tendency. difference between sleep () and yield () sleep () and yield (): sleep () causes the current thread to enter a standstill state, So the thread that executes sleep () is certainly not executed for the specified time, and yield () simply returns the current thread back to the executable state, so the thread that executes yield () is likely to be executed immediately after entering the executable state. The sleep method allows the currently running thread to sleep for a period of time, entering a non-operational state, which is programmed by the program,yield method causes the current thread to give up CPU possession, but the time to yield is not settable. In fact, the yield () method corresponds to the following actions: first detect if the thread with the same priority is currently in the same operational state, and if so, give the CPU 's possession to this thread, or continue to run the original thread. So the yield () method is called "concession," which gives the opportunity to other threads of equal priority Another,sleep method allows the lower-priority thread to get the run opportunity, but yield () when the method executes, the current thread is still in a running state, so it is not possible to give the lower priority thread some time to gain CPU possession. In a running system, if a higher priority thread does not have a call to the sleep method and is not blocked by I\O , then the lower priority thread can only wait for all higher priority threads to run to the end before the opportunity runs. Thread Synchronization 1, the purpose of thread synchronization is to protect multiple threads to access a resource when the resource is destroyed. 2, thread synchronization method is implemented by lock, each object has and only one lock, this lock is associated with a specific object, once the thread acquires an object lock, other threads that access the object can no longer access the object's other non-synchronous methods. 3, for the static synchronization method, the lock is for this class, the lock object is the class object. Static and non-static methods of locking do not interfere. A thread acquires the lock, which is obtained when a synchronization method on another object is accessed in a synchronous method. 4, for synchronization, to be awake at all times on which object synchronization, this is the key. 5, write thread-safe classes, you need to pay attention to multiple threads competing access to the logic and security of the resources to make the right judgment, the "atomic" operation to make an analysis, and ensure that other threads during atomic operation can not access the competing resources. 6. When multiple threads wait for an object lock, the thread that does not acquire the lock will block. 7, deadlock is between the threads waiting for lock-lock caused by, in practice, the probability of occurring is very small. However, once the program has a deadlock, the program will die. 1, synchronized the scope of the keyword two: 1) is an object instance, synchronized Amethod () {} can prevent multiple threads from accessing the Synchronized method for this object (if an object has multiple synchronized methods, as long as one thread accesses one of the synchronized methods, Other threads cannot access any one of the synchronized methods in this object at the same time. At this point, the synchronized method of the different object instances is not interfering. That is, other threads can still access the Synchronized method in another object instance of the same class; 2) is the scope of a class, synchronized static astaticmethod{} Prevents multiple threads from accessing the synchronized static method in this class at the same time. It can work on all object instances of the class. 2, in addition to the method before using the Synchronized keyword, the synchronized keyword can also be used in a chunk of the method, indicating that only the resources of this block are mutually exclusive access. The usage is: synchronized (this) {/* chunk */}, its scope is the current object, 3, synchronized keyword is not inherited, that is, the base class method synchronizedF () {} is not automatically synchronized F () {} in the inheriting class, but instead becomes F () {}. Inheriting a class requires that you explicitly specify one of its methods as the Synchronized method; a. Regardless of whether the Synchronized keyword is added to a method or an object, the lock it obtains is an object, not a piece of code or function as a lock-and the synchronization method is likely to be accessed by other threads ' objects. B Each object has only one lock (lock) associated with it. C The implementation of synchronization is a big cost to the system, and may even cause deadlocks, so try to avoid unnecessary synchronization control. Note: A 0-length byte array object will be more economical to create than any object-view compiled bytecode: generates a 0-length byte[] object with only 3 opcode, and object lock = new Object () requires 7 lines of opcode.
Java-based multi-threading