Comment Area leave a mailbox to get "Java multithreaded design mode in detail"
Reprint Please specify the source
1) Background Thread
A background thread is a thread that serves other threads, and a garbage collection thread like a JVM is a background thread. The background thread always waits until the non-background thread dies, the background thread does not have the service object, and soon it will die automatically, no longer resurrected. The Setdaemon method allows you to set a thread as a background thread, but it must be called before it is started.
For example:
/* * @author [email protected] */public class Daemonthread extends Thread {public void run () {for (int i=0; i<100; i + +) {System.out.println (GetName () + "" + i);}} public static void Main (string[] args) throws interruptedexception {Daemonthread dt = new Daemonthread ();d T.setdaemon (tru e);//Must call Dt.start () before starting the thread; System.out.println (Dt.isdaemon ());//truefor (int i=0; i<10; i++) {System.out.println (Thread.CurrentThread ()). GetName () + "" + i); Thread.Sleep (1000);//Let the current thread sleep 1s, into the blocking state. Other threads can execute}//in the main thread, and the background thread St will also die shortly after main threads}}
2) thread Concession: yield
Suspends the current thread, but does not block the thread. Put the thread into a ready state. The system re-dispatches threads based on priority. You can use the SetPriority method to set the priority of a thread.
For example:
public class Yieldthread extends Thread {public yieldthread (String name) {super (name);} public void Run () {for (int i=0; i<50; i++) {System.out.println (GetName () + "" + i); if (i = =) {Thread.yield ();//Let current thread Concession}}}public static void main (string[] args) {Yieldthread yt1 = new Yieldthread ("High"); Yieldthread yt2 = new Yieldthread ("Low"), yt1.setpriority (max_priority);//Priority set to Advanced Yt1.start (); Yt2.setpriority (Min_ Priority is set to low-level yt2.start ();}}
3) The difference between sleep and yield
When sleep pauses, it goes into a blocking state, and other threads execute, regardless of priority. When yield is paused, it enters the ready state. Only threads with the same or higher priority will be given the opportunity to execute.
4) thread synchronization
If two threads operate an account at the same time when the bank is taking money, an error should occur, which is that the thread is unsafe. So how can you make a thread safe?
public class Account {private string accountno;private double Balance;public account () {};p the Ublic account (String a,double b ) {Accountno = A;balance = b;} public void Setaccountno (String accountno) { this.accountno = Accountno;} public void setbalance (double balance) {this.balance = balance;} Public String Getaccountno () {return this.accountno;} Public double GetBalance () {return this.balance;} Override hashcode method public int hashcode () {return Accountno.hashcode ();} Override the Equals method public boolean equals (Object obj) {if (this = = obj) return true;if (obj! = null && obj.getclass () = = ACC Ount.class) {Account A = (account) Obj;return A.getaccountno (). Equals (Accountno); return false;}}
public class withdraw extends Thread{private account Account;private double drawno;public withdraw (String name, account A, Double d) {super (name); account = A;drawno = D;} public void Run () {//synchronized (account) {//Lock object, other threads cannot be obtained and cannot modify accounts. if (Account.getbalance () >= drawno) {System.out.println ("The amount taken is:" + drawno); try {thread.sleep ()} catch ( Interruptedexception e) {e.printstacktrace ();} Account.setbalance (Account.getbalance ()-Drawno); System.out.println ("Balance:" + account.getbalance ());} else {System.out.println ("failed to withdraw money! ");//}}}}
public class Drawmoney {public static void main (string[] args) {Account AC = new account ("Wangxu", +); new Withdraw ("a", AC, +). Start (); New Withdraw ("B", AC, +). Start ();}}
As shown in the code above, locks are required when modifying a problem that can cause thread insecurity. You can use the code synchronization block and synchronization method to lock, the keyword is synchronized. Do not repeat the details.
4) Sync Lock
In order to solve the thread safety problem more flexibly, Java introduces the synchronous lock. There are read and write locks, can be re-entered lock and so on.
To give a simple example:
Import Java.util.concurrent.locks.reentrantlock;public class Lock {private final Reentrantlock lock = new Reentrantlock ( )///Require thread-safe method public void F () {lock.lock ();//Locking try{//...} finally {lock.unlock ();//Release Lock}}}
About deadlocks and thread communication the next update.
Comment Area leave a mailbox to get "Java multithreaded design mode in detail"
Reprint Please specify the source
Java Multithreading in detail (ii)