Multithreading
The difference between multi-threading and multi-process is that each process has its own set of variables, and threads share data. Threads are more "lightweight" than processes, and it is much less expensive to create and revoke a thread than to start a new process.
There are two ways to implement multithreading:
- Implementing the Runnable Interface
- Inherit the thread class
The following two methods are used to implement multithreading
Implementing the Runnable Interface
Public classFootballImplementsrunnable{PrivateString player; Private Static intsteps=10; PublicFootball (String name) {player=name; } @Override Public voidrun () { while(true) {System.out.println (Thread.CurrentThread (). GetId ()+ ":" +player+ "is playing football"); Try{thread.currentthread (); Thread.Sleep (1200); } Catch(interruptedexception e) {e.printstacktrace (); } } }} Public classBasketballImplementsRunnable {PrivateString player; Private Static intSteps=20; PublicBasketball (String name) {player=name; } @Override Public voidrun () { while(true) {System.out.println (Thread.CurrentThread (). GetId ()+ ":" +player+ "is playing basketball"); Try{thread.currentthread (); Thread.Sleep (700); } Catch(interruptedexception e) {e.printstacktrace (); } } }} Public classPlay { Public Static voidMain (string[] args) {//TODO auto-generated Method StubRunnable foot =NewFootball ("Tom"); Runnable Basket=NewBasketball ("John"); Thread T1=NewThread (foot); Thread T2=NewThread (basket); T1.start (); T2.start (); }} Output:8: Tom is playing football9: John is playing basketball9: John is playing basketball8: Tom is playing football9: John is playing basketball9: John is playing basketball8: Tom is playing football9: John is playing basketball9: John is playing basketball8: Tom is playing football9:john is playing basketball
Inherit the thread class
Public classFootballextendsthread{PrivateString player; PublicFootball (String name) {player=name; } Public voidrun () { while(true) {System.out.println (Thread.CurrentThread (). GetId ()+ ":" +player+ "is playing football"); Try{thread.currentthread (); Thread.Sleep (1200); } Catch(interruptedexception e) {e.printstacktrace (); } } }} Public classBasketballextendsthread{PrivateString player; PublicBasketball (String name) {player=name; } Public voidrun () { while(true) {System.out.println (Thread.CurrentThread (). GetId ()+ ":" +player+ "is playing basketball"); Try{thread.currentthread (); Thread.Sleep (700); } Catch(interruptedexception e) {e.printstacktrace (); } } }} Public classPlay { Public Static voidMain (string[] args) {//TODO auto-generated Method StubThread T1 =NewFootball ("Tom"); Thread T2=NewBasketball ("John"); T1.start (); T2.start (); }} Output:8: Tom is playing football9: John is playing basketball9: John is playing basketball8: Tom is playing football9: John is playing basketball9: John is playing basketball8: Tom is playing football9: John is playing basketball9: John is playing basketball8: Tom is playing football9: John is playing basketball8:tom is playing football
Break Thread in
The thread is stopped when the thread's Run method executes to the end, or an uncaught exception occurs.
Can be passed Thread.CurrentThread (). interrupt () to force the termination of the current thread. When the method is called on a thread, the interrupt state of the thread is placed. We can then pass the Thread.CurrentThread (). isinterrupted () Check this flag to determine if the thread is interrupted.
However, if the thread is blocked (call sleep or wait), the interrupt state cannot be detected. When a blocked method calls the interrupt method, it is interrupted by an interruptedexception exception.
When the interrupt state is set, the sleep method is called, and he does not hibernate, but clears the state and throws a Interruptedexception exception.
//Change the football section code Public classFootballImplementsrunnable{PrivateString player; Private Static intsteps=10; PublicFootball (String name) {player=name; } @Override Public voidrun () { while(!Thread.CurrentThread (). isinterrupted ()) {Steps--; System.out.println (Thread.CurrentThread (). GetId ()+ ":" +player+ "is playing football"); Try{thread.currentthread (); Thread.Sleep (800); } Catch(interruptedexception e) {e.printstacktrace ();} if(steps<=0) {Thread.CurrentThread (). interrupt (); Set Interrupt flag Try{Thread.Sleep (800); the interrupt flag is set in front of//, so a interruptedexception exception is called here } Catch(interruptedexception e) { //Interruptedexception exception occurs, the interrupt flag is cleared System.out.println ("VVVVVVVVVVVVVVVVVVVVVVVV"); System.out.println ("Thread:" +thread.currentthread (). GetId () + "Call the Sleep method an exception occurred!" "); Try{Thread.Sleep (800); //Because the interrupt flag is cleared, the call here is no problem System.out.println ("Thread:" +thread.currentthread (). GetId () + "Call the Sleep method successfully!" "); } Catch(Interruptedexception E1) {} System.out.println ("^^^^^^^^^^^^^^^^^^^^^^^^"); }}} System.out.println ("The Footbal thread is terminated!" "); }}
Output
9: John is playing basketball9: John was playing basketball8: Tom is playing football9: John Is playing basketball8: Tom was playing football9: John is playing BASKETBALLVVVVVVVVVVVVVVVVVVVVVVVV Thread:8 Calling the Sleep method an exception occurred! 9: John is playing basketball thread:8 Call the Sleep method successfully! ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ 8 ^^ ^^ ^^, Tom was playing football9:john is playing basketball
Thread state
There are 6 states of thread
-
- Newly created
- Can run
- Be blocked
- Wait
- Timed wait
- Be terminated
Five phases: Create, ready, run, block, terminate
New Thread
New Thread (r) newly created one, but not yet running.
Can run threads
Call the Start () method, and the thread is in the runnable state. May or may not be running. Depends on the system.
Blocking threads
When a thread attempts to acquire an internal object lock that is held by another thread, the thread is in a blocked state. When the lock is freed by another thread, and the thread scheduler allows this thread to hold it, the thread becomes a non-blocking state.
Waiting for thread
When a thread waits for another thread to notify the scheduler of a condition, it enters its own wait state. This occurs when you call the Object.wait method or the Thread.Join method, or wait for lock or condition in the Java.util.concurrent library.
Timed wait
There are several methods that have a timeout parameter, and calling them causes the thread to enter a timed wait. such as Thread.Sleep (), object.wait,thread.join,lock.trylock,condition.await.
Terminating a thread
Here are two possibilities:
died because the Run method exited gracefully.
Unexpected death by terminating the Run method because of an uncaught exception.
You can call Thread.CurrentThread (). Join () or Thread.CurrentThread (). Join (long Millis) to wait for the process to terminate.
Thread state diagram
Thread state transitions
Thread Properties
(18) Multithreading