Threads are different execution branches within a program, there are two main ways to implement multithreading: Inherit from the thread class or implement Runnable interface, in fact, the thread class is also implemented Runnable interface, based on Java single inheritance mechanism, We recommend implementing the thread class in a way that implements Runnable, where there is only one run method in the Runnable interface, the thread class must implement this method, and the multithreaded business logic is written in the Run method.
Transition of thread State:
New Thread (runnable);
This creates a thread, noting that runnable is the thread class that implements the Runnable interface
T.start ();
When a thread enters a ready state, when it is called depends on the CPU's "mood" (thread priority, CPU rush, and so on), the CPU dispatches the thread to make the thread run, executing the thread class's Run method. The thread may go into a blocking state when it is running, such as calling Thread.Sleep ()/wait () or the program throws a interruptedexception in code, etc., and the thread will automatically exit when the thread does not meet certain conditions. It is strongly not recommended to use the deprecated stop method to kill threads, which can cause many problems, such as some resources may no longer be properly closed.
IsAlive (): Check if the thread is still alive, a thread that is alive if it has not been terminated.
Public classIsAlive { Public Static voidMain (string[] args)throwsinterruptedexception {myrunnable myrunnable=Newmyrunnable (); Thread MyThread=NewThread (myrunnable); System.out.println ("1. MyThread isAlive?" +mythread.isalive ()); Mythread.start (); System.out.println ("2. MyThread isAlive?" +mythread.isalive ()); Thread.Sleep (3000); System.out.println ("3. MyThread isAlive?" +mythread.isalive ()); }}classMyrunnableImplementsRunnable {@Override Public voidrun () { for(inti = 0; I < 5; i++) {System.out.println ("Myrunnable.run i =" +i); } }}
The role of the setpriority and GetPriority methods is to set the thread priority and get the thread priority, the thread has priority, the level is from 1 to 10,1 to the lowest level, after the thread is created, the default priority is 5, The thread class defines 3 int constants to represent the lowest, highest, and default levels of a thread:
/*** The minimum priority, a thread can have. */ Public Final Static intmin_priority = 1; /*** The default priority, which is assigned to a thread. */ Public Final Static intNorm_priority = 5; /*** The maximum priority, a thread can have. */ Public Final Static intMax_priority = 10;
Public classPriority { Public Static voidMain (string[] args) {MyRunnable1 myrunnable=NewMyRunnable1 (); Thread MyThread=NewThread (myrunnable); System.out.println ("Default Level:" +mythread.getpriority ()); Mythread.setpriority (thread.norm_priority+ 3); System.out.println ("New level:" +mythread.getpriority ()); }}classMyRunnable1ImplementsRunnable {@Override Public voidrun () {}}
The higher the priority of a thread, the more time slices the CPU allocates for it.
Thread.Sleep (): Allows the current thread to sleep for a specified number of milliseconds
Use Thread.Sleep (1000) to do a timer-like function
Public classSleep { Public Static voidMain (string[] args) {MyRunnable3 myrunnable=NewMyRunnable3 (); Thread MyThread=NewThread (myrunnable); Mythread.start (); }}classMyRunnable3ImplementsRunnable {@Override Public voidrun () { for(inti = 0; I < 5; i++) {System.out.println (NewDate ()); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } } }}
Join (): Joins the thread to the current main thread to execute, waiting for the end of the join thread, which is equivalent to a method call.
If I do not use the Join method, you will see that the main thread and the branch thread are running concurrently:
Public classJoin { Public Static voidMain (string[] args)throwsinterruptedexception {MyRunnable4 myrunnable=NewMyRunnable4 (); Thread MyThread=NewThread (myrunnable); Mythread.start ();//Mythread.join (); for(inti = 0; I < 3; i++) {System.out.println ("I want to run, too."); Thread.Sleep (500); } }}classMyRunnable4ImplementsRunnable {@Override Public voidrun () { for(inti = 0; I < 3; i++) {System.out.println ("Run after me."); Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace (); } } }}
If I now counter-annotate the Mythread.join () line, you will find that the program executes the split route and then executes the print statements in the main thread:
This effect is the same as the following code, which is the normal method invocation:
Public classJoin { Public Static voidMain (string[] args)throwsinterruptedexception {MyRunnable4 myrunnable=NewMyRunnable4 (); Myrunnable.run (); for(inti = 0; I < 3; i++) {System.out.println ("I want to run, too."); Thread.Sleep (500); } }}classMyRunnable4ImplementsRunnable {@Override Public voidrun () { for(inti = 0; I < 3; i++) {System.out.println ("Run after me."); Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace (); } } }}
Yield (): Let the thread "sharp sense" out of CPU resources to other threads.
How the deadlock problem occurs:
Assuming we have two threads Thread1 and Thread2, there are two synchronized objects Obja and OBJB, Thread1 execution needs to lock Obja and then lock OBJB to perform the operation before it can complete the task and release the lock, Thread2 instead, It needs to lock OBJB and then lock Obja to complete the task, when Thread1 execution found that OBJB was Thread2 locked, so only wait, and Thread2 view to lock Obja when the object was Thread1 locked, So Thread2 can only wait, so two objects are waiting for each other to release the lock, which creates a deadlock, a deadlock solution is to achieve a coarse-grained lock, do not lock on multiple objects at the same time.
Synchronized: Take a look at a classic face test
1 Public classThreadinterviewImplementsRunnable {2 3 Private inti = 100;4 5 Public synchronized voidFoo1 ()throwsinterruptedexception {6i = 1000;7Thread.Sleep (3000);8System.out.println ("foo1 i =" +i);9 }Ten One Public voidFoo2 () { ASystem.out.println ("Foo2 i =" +i); - } - the Public Static voidMain (string[] args)throwsinterruptedexception { -Threadinterview ti =NewThreadinterview (); -Thread T =NewThread (TI); - T.start (); +Thread.Sleep (1000); - Ti.foo2 (); + } A at @Override - Public voidrun () { - Try { - foo1 (); -}Catch(interruptedexception e) { - e.printstacktrace (); in } - } to}
Q What is the value of 20 line I?
The answer is 1000, why not 100, where is the test center of the problem? Foo1 is a synchronous method, when the thread T executes this method will be the Ti object lock, but Foo2 is not a synchronous method, the main thread can still access through the Foo2 I this is worthwhile, because of the order of execution problems, I in the foo1 is executed when the change to 1000, Of course I in Foo2 is also 1000. The test point is that the synchronization method locks the object at the time other threads can still access their unsynchronized methods.
What is the difference between thread.sleep () and object.wait ()?
When the thread is asleep, the thread wakes up after the specified number of milliseconds, the thread still holds the lock, and when the thread is waiting, the thread does not wake up unless there is a notify method that invokes the thread, and wait, the lock is no longer owned by that thread.
Notify method: Wakes the thread that is currently being wait.
Java Thread Small note