Java thread Summary (2)

Source: Internet
Author: User

6. interrupt () interrupts the Thread. If a Thread throws an exception, interrupt can be used to interrupt the Thread in catch. 7. The constructor Thread () allocates a new Thread object. Thread (Runnable target) allocates a new Thread object. Thread (Runnable target, String name) allocates a new Thread object. Thread (String name) 8. Common method static Thread currentThread () returns a reference to the currently executed Thread object. String getName () returns the name of the thread. Void setName (String name) changes the thread name to be the same as the parameter name. Int getPriority () returns the priority of the thread. Void setPriority (int newPriority) changes the priority of a thread. Void interrupt () interrupt thread. Boolean isAlive () is used to test whether the thread is active. Boolean isDaemon () to test whether the thread is a daemon thread. Void join () waits for the thread to terminate. Void join (long millis) waits for the thread to terminate for a maximum of millis milliseconds. Void run () if the thread is constructed using an independent Runnable running object, the run method of the Runnable object is called; otherwise, the method does not perform any operation and returns the result. Void setDaemon (boolean on) marks the thread as a daemon or user thread. Void start () enables the thread to start execution; Java Virtual Machine calls the run method of the thread. Static void yield (): Pause the currently executing thread object and execute other threads. 9. The ThreadGroup class is used to represent a thread group. It can classify and manage a batch of threads. Java allows the program to directly control the thread group. Case: package com. xiaomo. thread; public class ThreadGroupTest {public static void main (String [] args) throws InterruptedException {// gets the thread group of the main thread, this is the default Thread group ThreadGroup mainGroup = Thread. currentThread (). getThreadGroup (); System. out. println ("main thread group name:" + mainGroup. getName (); System. out. println ("whether the main thread group is a background thread group:" + mainGroup. isDaemon (); new MyThread ("new thread group"); ThreadGroup tg = new ThreadGroup (" New thread group "); tg. setDaemon (true); System. out. println ("Whether the tg thread group is a background thread group:" + tg. isDaemon (); MyThread tt = new MyThread (tg, "tg group thread a"); tt. start (); // Interrupt all processes in the thread group // tg. interrupt (); // Thread. sleep (20); // returns the number of active threads // System. out. println (tg. activeCount (); // sets the priority of the thread group // tg. setMaxPriority (Thread. MAX_PRIORITY); // gets the priority of the thread group // System. out. println (tg. getMaxPriority (); new MyThread (tg, "tg group thread B "). start () ;}} class MyThread extends Thread {// provides the public MyThread (String name) {super (name) ;}// specifies the Thread name, the constructor of the thread group is public MyThread (ThreadGroup group, String name) {super (group, name);} public void run () {for (int I = 0; I <20; I ++) {System. out. println (getName () + "thread I variable" + I) ;}}10. Thread-synchronized multi-thread programming in Java is often prone to sudden errors, this is because the system's thread scheduling is random, even if the program occasionally encounters problems during the running process, it is caused by improper programming. When multiple threads are used to access the same data, thread security issues are very likely to occur, so we use a synchronous mechanism to solve these problems. There are two ways to implement the synchronization mechanism: 1. synchronous code block: synchronized (same data) {} the same data: that is, N threads access one data at the same time. 2. synchronous method: public synchronized data return type method name () {} is to use synchronized to modify a method, this method is called a synchronous method. For the synchronization method, you do not need to display the specified synchronization monitor. The synchronization monitor of the synchronization method is this, that is, the object itself. By using the synchronization method, A class can be easily converted into a thread-safe class with the following features: 1. Objects of this class can be securely accessed by multiple threads. 2. After each thread calls any method of the object, the correct result is obtained. 3. After each thread calls any method of the object, the state of the object remains reasonable. Note: The synchronized keyword can be used to modify methods or code blocks, but not constructors and attributes. Pay attention to the following points for implementing the synchronization mechanism: high security, low performance, and multithreading. High performance, low security, used in a single thread. 1. Do not synchronize all methods of the thread security class, but only those that will change the shared resource method. 2. If there are two runtime environments for the variable class, two versions should be provided for the variable class when the thread environment and the multi-thread environment: thread-safe version and thread-unsafe version (no synchronization method and synchronization block ). In a single thread environment, the thread-safe version is used to ensure performance, and the thread-safe version is used in multithreading. java. lang. the three methods (wait () y () notifyAll () wait) in the object cause the current thread to wait until other threads call the notify method or yyall method of the synchronization monitor to wake up the thread. The wait (mills) method automatically wakes up after a specified time. The current thread that calls the wait method will release the lock of the synchronization monitor. You do not need to use the Y or notifyAll method to wake it up. Y () wakes up a single thread waiting on the synchronization monitor. If all threads are waiting on the synchronization monitor, it will wake up one of the threads and the choice is arbitrary, the wake-up thread can be executed only when the current thread stops locking the synchronization monitor, that is, the wait method is used. The yyall () method wakes up all threads waiting on the synchronization monitor. Only when the current thread stops locking the synchronization monitor can the thread be awakened. Example: package com. xiaomo. thread; import java. util. concurrent. locks. condition; import java. util. concurrent. locks. lock; import java. util. concurrent. locks. reentrantLock; public class Account {// encapsulate Account number, Account balance two Fieldprivate String accountNo; private double balance; // indicates whether there is a deposit in the Account private boolean flag = false; // display the definition Lock Object private final Lock lock = new ReentrantLock (); // obtain the specified Lo The ck object corresponds to Conditionprivate final Condition cond = lock. newCondition (); // defines the Lock Object private final ReentrantLock relock = new ReentrantLock (); // constructor public Account () {} public Account (String accountNo, double balance) {this. setAccountNo (accountNo); this. setBalance (balance);} public int hashCode () {return accountNo. hashCode ();} // The following two methods use accountNo to override the hashCode () and equals () Methods public boolean equals (Object obj) {if (This = obj) {return true;} if (obj! = Null & obj. getClass () = Account. class) {Account target = (Account) obj; return target. getAccountNo (). equals (accountNo);} return false;} // provides a thread-safe draw method to complete the money Acquisition operation (synchronous method) public synchronized void draw (double drawAmount) {// the account balance is greater than the amount of money charged if (balance> = drawAmount) {// spit out the real bill System. out. println (Thread. currentThread (). getName () + "money Acquisition successful! Spit out real money: "+ drawAmount); try {Thread. sleep (1);} catch (InterruptedException e) {e. printStackTrace ();} // modify balance-= drawAmount; System. out. println ("\ t balance:" + balance);} else {System. out. println (Thread. currentThread (). getName () + "failed to get money! Insufficient balance! ") ;}} // Provides a thread-safe draw method to complete the money Acquisition operation (Synchronous lock) public void acquire (double drawAmount) {// lock relock. lock (); try {if (balance> = drawAmount) {// spit out the real bill System. out. println (Thread. currentThread (). getName () + "money Acquisition successful! Spit out real money: "+ drawAmount); try {Thread. sleep (1);} catch (InterruptedException e) {e. printStackTrace ();} // modify balance-= drawAmount; System. out. println ("\ t balance:" + balance);} else {System. out. println (Thread. currentThread (). getName () + "failed to get money! Insufficient balance! ") ;}} Finally {// Modification complete, release lock relock. unlock () ;}// the thread communication mode of the synchronization method public synchronized void get (double drawAmount) {try {// if the flag is false, it indicates that no one has saved money in the account, and the method of obtaining the money is blocked if (! Flag) {this. wait ();} else {if (balance> = drawAmount) {// perform the money Acquisition operation System. out. println (Thread. currentThread (). getName () + "money Acquisition:" + drawAmount); balance-= drawAmount; System. out. println ("account balance:" + balance); // set the flag indicating whether the account has a deposit to falseflag = false; // wake up other threads this. policyall ();} else {System. out. println (Thread. currentThread (). getName () + "failed to get money! Insufficient balance! ") ;}} Catch (InterruptedException e) {e. printStackTrace () ;}// the thread communication mode of the synchronization method public synchronized void deposit (double drawAmount) {try {// if the flag is true, it indicates that someone in the account has saved money, saving Method blocking if (flag) {this. wait ();} else {// executes the deposit operation System. out. println (Thread. currentThread (). getName () + "Save Money:" + drawAmount); balance + = drawAmount; System. out. println ("account balance:" + balance); // sets the flag indicating whether the account has a deposit to trueflag = true; // wake up other threads this. policyall () ;}} Catch (InterruptedException e) {e. printStackTrace () ;}// Synchronous lock mode for thread communication public void getLock (double drawAmount) {lock. lock (); try {// if the flag is true, it indicates that someone in the account has saved the money, and the saving method is blocked if (! Flag) {cond. await ();} else {if (balance> = drawAmount) {// perform the money Acquisition operation System. out. println (Thread. currentThread (). getName () + "money Acquisition:" + drawAmount); balance-= drawAmount; System. out. println ("account balance:" + balance); // set the flag indicating whether the account has a deposit to falseflag = false; // wake up other threads cond. signalAll ();} else {System. out. println (Thread. currentThread (). getName () + "failed to get money! Insufficient balance! ") ;}} Catch (InterruptedException e) {e. printStackTrace ();} finally {lock. unlock () ;}// Synchronous lock mode for thread communication public void depositLock (double drawAmount) {lock. lock (); try {// if the flag is true, it indicates that someone in the account has saved the money, and the saving method is blocked if (flag) {cond. await ();} else {// executes the deposit operation System. out. println (Thread. currentThread (). getName () + "Save Money:" + drawAmount); balance + = drawAmount; System. out. println ("account balance:" + balance); // sets the flag indicating whether the account has a deposit to trueflag = true; // wake up other threads cond. signalAll () ;}} catch (InterruptedException e) {e. printStackTrace ();} finally {lock. unlock () ;}} public String getAccountNo () {return accountNo;} public void setAccountNo (String accountNo) {this. accountNo = accountNo;} public double getBalance () {return balance;} public void setBalance (double balance) {this. balance = balance ;}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.