Thread (java class notes), thread java class notes

Source: Internet
Author: User
Tags set background

Thread (java class notes), thread java class notes
1. differences between the two methods 2. thread lifecycle 3. thread control (thread method) 4. thread Synchronization 5. differences between Thread synchronization locks 1 and 2 Methods A extends Thread: simply cannot inherit other classes (Java single inheritance) the same resource does not share B implements Runnable :( recommended )) multiple threads share one target resource, which is suitable for processing the same resource in multiple threads. This class can inherit other classes or implement other interfaces. 2. new thread lifecycle: when the program uses new to create a thread, the thread is in the new State. At this time, it is the same as other java objects, only the Java Virtual Machine allocates memory for it and initializes the member variable value. [Thread r = new Thread ()] Ready: When the Thread object calls the start () method, the Thread is in the ready state, and the Thread is included in the Thread queue, at this time, the thread in this status does not start execution. It only indicates that it can run. When the thread runs depends on the scheduling of the JVM thread scheduler. [R. start ()] run: If the ready thread obtains the CPU, it starts to execute the run () thread execution body, and the thread is in the execution state. Blocking: the thread needs to be interrupted during running, so that other threads can get execution opportunities. This status will enter the blocking status. Note: The blocking status cannot be changed directly to the running status. The blocking status can only be changed to the ready status again. Death: run () execution is complete, and the thread ends normally; the thread throws an uncaptured Exception or Error; the stop () of the calling thread (). (Easy to cause deadlocks, not recommended) Note: after the main thread ends, other threads are not affected and will not end. Once the sub-thread starts, it will have the same status as the main thread, it is not affected by the main thread. Example: class MyThread implements Runnable {public void run () {for (int I = 0; I <200; I ++) {System. out. println (I) ;}} public class MyThreadDemo {public static void main (String [] args) {for (int I = 0; I <10; I ++) {if (I = 5) {MyThread t = new MyThread (); new Thread (t ). start ();} System. out. println ("main" + I) ;}} test whether the thread is alive. The isAlive () method of the thread object is available. When the thread is in the ready state, running, blocking status returns true. If the thread is in the new and dead state, false is returned. It is impossible for a dead thread to wake up a thread through the start () method. Otherwise, the IllegalThreadStateException is thrown. public class DieThreadDemo {public static void main (String [] args) {DeadThread dt = new DeadThread (); for (int I = 0; I <100; I ++) {Thread mainThread = Thread. currentThread (); // obtain the current thread (Main thread) System. out. println (mainThread. getName () + "--" + I); System. out. println ("------>" + mainThread. isAlive (); if (I = 10) {dt. start () ;}} if (! Dt. isAlive () {dt. start () ;}} class DeadThread extends Thread {public void run () {for (int I = 0; I <50; I ++) {System. out. println (getName () + "--" + I) ;}} 3. Thread-controlled Join () method: Wait for the thread to terminate. Join method: the thread object that calls the join method is forced to run. Other threads cannot run during the force running of the thread. Other threads can run only after the thread ends. Some people also regard this method as an overloaded method of the join method of the joint thread: join (long millis): join (long millis, int nanos): Usually the third method is rarely used: the program does not need to be accurate to one second. The computer hardware and operating system cannot be accurate to one second. public class JoinDemo {public static void main (String [] args) throws Exception {Thread join = new Thread (newJoin (), "Join Thread"); join. start (); int I = 0; while (I <500) {if (I = 100) {join. join ();} System. out. println ("Main -->" + I ++) ;}} class Join implements Runnable {public void Run () {int I = 0; while (I <200) {System. out. println (Thread. currentThread (). getName () + "--" + I ++) ;}} setDaemon () method background thread: running in the background, the task is to provide services for other threads. It is also called "daemon thread" or "Genie thread ". JVM garbage collection is a typical background thread. Features: If all foreground threads die, background threads automatically die. Set background Thread: the Thread object setDaemon (true); setDaemon (true) must be before start. Otherwise, an exception occurs in IllegalThreadStateException. The Thread created by the foreground Thread is the foreground Thread by default. Determine whether the Thread is a background Thread: Use the isDaemon () method of the Thread object; the new thread is the background thread only when the creation thread is a background thread. Class Daemon extends Thread {public void run () {for (int I = 0; I <10000; I ++) {System. out. println (getName () + "-" + I) ;}} public class DaemonDemo {public static void main (String [] args) {Daemon d = new Daemon (); d. setDaemon (true); // set the d thread to the background thread d. start (); for (int I = 0; I <5; I ++) {System. out. println (Thread. currentThread (). getName () + "--" + I) ;}} Sleep () thread Sleep: suspend the thread for a period of time and enter the blocking state. Sleep (long milllis) throws InterruptedException: millisecond sleep (long millis, int nanos) throws InterruptedException: millisecond. After a nanosecond calls sleep (), within a specified period of time, this thread will not receive execution opportunities. Public class SleepDemo {public static void main (String [] args) {for (int I = 10; I> 0; I --) {System. out. println ("remaining" + I); try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace () ;}}}4. thread priority each thread has a priority. The priority is only related to the number of times the thread gets the execution opportunity. The higher the thread priority, it must be executed first. The first running of a thread depends on the CPU scheduling. By default, the main thread has a normal priority, and the thread it creates has a normal priority. SetPriority (int x) and getPriority () of the Thread object to set and obtain the priority. MAX_PRIORITY: The value is 10MIN_PRIORITY: The value is 1NORM_PRIORITY: The value is 5 (the default Priority of the main method) class Priority extends Thread {public void run () {for (int I = 0; I <100; I ++) {System. out. println (getName () + ", priority =" + getPriority () + "--" + I) ;}} public class PriorityDemo {public static void main (String [] args) {Thread. currentThread (). setPriority (7); for (int I = 0; I <100; I ++) {if (I = 10) {Priority p1 = new Priority (); p1. SetPriority (Thread. MAX_PRIORITY); p1.start () ;}if (I = 15) {Priority p2 = new Priority (); p2.setPriority (Thread. MIN_PRIORITY); p2.start ();} System. out. println ("main" + I) ;}} Yield () method Thread courtesy: Pause the currently executing Thread object and execute other threads; static method of Thread, it can be that the current thread is paused, but the thread is not blocked, but enters the ready state. Therefore, it is entirely possible that after a thread calls yield (), the thread scheduler schedules it again and re-executes it. Class Yield implements Runnable {public void run () {for (int I = 0; I <100; I ++) {System. out. println (Thread. currentThread (). getName () + "-->" + I); if (I % 2 = 0) {Thread. yield (); // courtesy }}} public class YieldDemo {public static void main (String [] args) {Yield y = new Yield (); new Thread (y, ""). start (); new Thread (y, "C "). start () ;}} API obsolete method-Easy deadlock, stop is not recommended: Terminate the thread to immediately stop the thread and release the lock held by the thread. This operation Failed to ensure that the internal status of the object is correct; suspend: The thread is suspended and the thread enters the "blocking" State. In this state, the CPU is not allocated to the thread time slice, this status can be used to pause the running of a thread. It is unavailable before being called by the resume method. if you want the target thread of suspend to lock an important system resource, no thread can use this resource until the target thread of suspend is resumed. Resume: The Restoration thread resumes being suspended by the suspend method. Java2 has discarded the suspend () and resume () methods, because using these two methods may lead to deadlocks, so we should use the synchronous object to call the wait () and Policy () mechanisms instead of suspend () and resume () for thread control. 5. The cause of the security problem caused by the thread security problem: there is a delay in the access of multiple threads. Random threads. Note: in ideal conditions, thread security problems are not easy to occur, but the impact on software is very large once they occur. We can use the Thread. sleep (long time) method to simulate latency. 6. Thread Synchronization when multiple threads access the same data, thread security issues may occur. So that multiple operations can only be performed by one thread in the same time period. Other threads can continue to execute until the thread is completed. Typical Example: the user enters the withdrawal amount for the bank to withdraw money. The system determines whether the balance is greater than the withdrawal amount. If the balance is greater than the withdrawal amount, the withdrawal is successful. If the balance is less than the withdrawal amount, the withdrawal fails. Example Analysis: Account class: Account Field balance indicates the balance for money collection class: DrawMoney Thread class field a indicates the Account object, and money indicates the amount to be retrieved; put the money collection behavior in the thread body; prompt: public void run () {if (c. getBlance ()> = money) {System. out. println (getName () + ", remove" + money); Thread. sleep (100); c. setBlance (c. getBlance ()-money); System. out. println ("balance =" + c. getBlance ();} else {System. out. println (getName () + "insufficient balance, balance" + c. getBlance () + ", need to take away" + money) ;}solve the problem: Method 1: When the above situation occurs, java provides us with the synchronous code block synchronized (obj) {// obj indicates the synchronization Monitor, which is the same synchronization object /**..... todo something */} Method 2: synchronized return value type method name (parameter list ){/**..... the synchronization listener of the todo something */} synchronization method is actually this/*** Account **/public class Account {/*** balance */private double blance; public Account (double blance) {this. blance = blance;} public double getBlance () {return blance;} public void setBlance (double blance) {this. blance = blance;} public synchronized void draw (doubledrawMoney) {if (getBlance ()> = drawMoney) {System. out. println (Thread. currentThread (). getName () + ", retrieve" + drawMoney); try {Thread. sleep (1);} catch (InterruptedException e) {e. printStackTrace ();} // modify the balance setBlance (getBlance ()-drawMoney); System. out. println ("balance =" + getBlance ();} else {System. out. println ("Sorry for insufficient balance"); }}/ *** money Acquisition operation */public class DrawThread extendsThread {/*** Account */private Account; /*** get the money */public double drawMoney; public DrawThread (String name, Account a, double drawMoney) {super (name); this. a = a; this. drawMoney = drawMoney;}/*** when multiple threads modify data of the same shared resource, data security issues will occur */public void run () {/* synchronized (a) {if (. getBlance ()> = drawMoney) {System. out. println (getName () + ", retrieve" + drawMoney); try {Thread. sleep (1);} catch (InterruptedExceptione) {e. printStackTrace ();} // modify the balance. setBlance (. getBlance ()-drawMoney); System. out. println ("balance =" +. getBlance ();} else {System. out. println ("Sorry for insufficient balance");} */. draw (drawMoney) ;}} the above content is the homework of the day after the class notes: The program for ticket sales requires three windows, a total of 50 tickets, random ticket sales, the probability that James will buy a ticket in each window after the purchase is sold out:

Public class Dome {// main class
Public static void main (String [] args) {// main method
Chuangkou c1 = new Chuangkou ("Window 1 ");
Chuangkou c2 = new Chuangkou ("window 2 ");
Chuangkou c3 = new Chuangkou ("window 3 ");
Thread t1 = new Thread (c1); // create three new threads
Thread t2 = new Thread (c2 );
Thread t3 = new Thread (c3 );
T1.start (); // three threads run simultaneously
T2.start ();
T3.start ();
}
}

Public class Piao {// used to count the number of votes
Public static String name = "this is the only option currently ";
Public static int piao = 1;
}

Public class Chuangkou implements Runnable {// window class
Public String name;
Static int a = 0; // defines three static variables to count the total number of tickets sold in each window.
Static int B = 0;
Static int c = 0;
Public Chuangkou (String name) {// parameter Constructor
This. name = name;
}
Public void run () {// run Method
While (Piao. piao <49) {// stop if the number of votes equals 49
Try {
Thread. sleep (1/10); // tested sleep 1/10 of the time is most conducive to the ticket sales rate for each window
} Catch (InterruptedException e ){
E. printStackTrace ();
}
Synchronized (Piao. name) {// synchronous to prevent multiple threads from running at the same time
System. out. println (name + "sold" + Piao. piao ++ "");
}
Switch (name) {// count the number of votes in the window
Case "Window 1": a + = 1; break;
Case "window 2": B + = 1; break;
Case "window 3": c + = 1; break;
}
}
System. out. println (name + "sold out ");
If (Piao. piao = 50) {// calculate the probability of James purchasing tickets
System. out. println ("the probability of James buying window 1 is" + (a/50.0 ));
System. out. println ("the probability of James buying window 2 is" + (B/50.0 ));
System. out. println ("the probability of James buying window 3 is" + (c/50.0 ));
}

}
}

At present, there are still problems with this assignment. I wonder why James's efficiency sometimes appears twice, sometimes not. I hope you can give me some guidance.

Related Article

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.