Threads (Java class notes)

Source: Internet
Author: User

1. Two ways of difference 2. Thread Lifecycle 3. Thread-based programming (threading method) 4. Threading Synchronization 5. Thread synchronization lock One, two ways of difference a extends thread: simple can no longer inherit other classes (Java single inheritance) the same share of resources do not share B implements Runnable: ( Recommended) Multiple threads share a target resource and are suitable for multithreading the same resource. This class can also inherit other classes, or implement other interfaces. The life cycle of a thread new: When the program uses new to create a thread, the thread is in the new state, and he, like other Java objects, allocates memory for it and initializes the member variable values for it only by the Java virtual machine. "Thread r = new Thread ()" Ready: When the thread object calls the start () method, the thread is in a ready state, the thread counts into the thread queue, and the state thread does not start executing, it only means that it is ready to run. As to when the thread is running, it depends on the JVM thread Scheduler Dispatch. "R.start ()" Runs: If a thread in the ready state gets the CPU, it starts executing the run () thread execution and the thread is in the execution state. Blocking: The thread needs to be interrupted during the run, in order to be the opportunity for other threads to execute. The state will go into a blocking state. Note: The blocking state cannot be directly turned into a running state, and the blocking state can only be re-entered in the ready state. Death: Run () execution completes, thread ends normally, thread throws uncaught exception or error, call thread's stop (). (Easy to cause deadlock, not recommended) Note: After the main thread ends, the other threads are unaffected and will not end, and once the child threads start up, they have the status of the main thread threads, and are 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);   }}} to test whether the thread is alive, the IsAlive () method of the Thread object is available. When the thread is ready to run, the blocking state returns true. Returns False when the thread is in new and dead state. The dead thread is not likely to wake the thread through the start () method. Otherwise, the illegalthreadstateexception exception is thrown; public class Diethreaddemo {public static void main (String[]args) {Deadthread dt =    New Deadthread (); for (int i = 0; i < i++) {thread mainthread =thread.currentthread ();//Get current thread (main thread) System.out.println      (Mainthread.getname () + "--" + i);      SYSTEM.OUT.PRINTLN ("------>" +mainthread.isalive ());      if (i = = ten) {Dt.start ();    }} if (!dt.isalive ()) {Dt.start (); }}}class Deadthread extends Thread {public void run () {for (int i = 0; i <; i++) {System.out.println (g    Etname () + "--" + i); }}} Three, thread control join () method: waits for the thread to terminate. Join method: The thread object calling the Join method is forced to run, the thread is forced to run, the other threads cannot run, and the other thread must wait until the thread finishes to run. Some people also make this way an overloaded method of the Union thread join method: Join (Long Millis): Join (Long Millis,int Nanos): A third method is often seldom used: The program does not need to be accurate to a nanosecond;    Neither the computer hardware nor the operating system can be accurate to one nanosecond; 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 <) {if (i = =) {Join.join ();    } System.out.println ("Main-->" + i + +);    }}}class Join implements Runnable {public void run () {int i = 0;    while (i<) {System.out.println (Thread.CurrentThread (). GetName () + "--" + i + +); The}}setdaemon () method background thread: Runs in the background, and the task is to serve other threads. Also known as "daemon thread" or "Sprite thread". Garbage collection of the JVM is a typical background thread. Feature: If all foreground threads are dead, the background thread automatically dies. Set Background thread: Thread Object Setdaemon (True); Setdaemon (true) must be before the start () call. Otherwise, a illegalthreadstateexception exception occurs, the thread created by the foreground thread defaults to the foreground thread, and the background thread: the Isdaemon () method that uses the thread object, and if and only if the creation thread is a background thread, The new line friend 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 D thread as Background thread d.start (); for (int i = 0; i < 5; i++) {System.out.println (thread.cuRrentthread (). GetName () + "--" + i); }}sleep () thread hibernation: lets the executing thread pause for a period of time and into a blocking state. Sleep (long Milllis) throws Interruptedexception: milliseconds sleep (long millis,int Nanos) throws Interruptedexception: milliseconds, After a nanosecond calls sleep (), the thread does not get an opportunity to execute within the specified time period. public class Sleepdemo {public static void main (String[]args) {for (int i = ten; i > 0; i--) {System.out.pri      Ntln ("Still remaining" + i);      try {thread.sleep (1000);      } catch (Interruptedexception e) {e.printstacktrace (); }}}} Four, thread priority each thread has a priority, and the priority level is only related to the number of times the thread gets the execution opportunity. Not the higher the priority of the thread must be executed first, which thread's first run depends on the CPU's dispatch; By default, the main thread has a normal priority, and the thread it creates has a normal priority. The thread object's setpriority (int x) and getpriority () to set and get precedence. Max_priority: Value is 10min_priority: value is 1norm_priority: value is 5 (Main method default priority) class priorities extends thread{public void run () {f    or (int i = 0; i < 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 = =) {Priority P1 = new priority ();        P1.setpriority (thread.max_priority);      P1.start ();        } if (i = =) {Priority P2 = new priority ();        P2.setpriority (thread.min_priority);      P2.start ();    } System.out.println ("main" + i); }}yield () method thread comity: Pauses the currently executing thread object and executes another thread, and the thread's static method, which can be paused by the current thread, but does not block the thread, but enters the ready state. So it is entirely possible that after a thread invokes yield (), the thread scheduler dispatches him again to execute. Class Yield implements Runnable {public void run () {for (int i = 0; i <; i++) {System.out.println (Threa      D.currentthread (). GetName () + "--" + i); if (i% 2 = = 0) {Thread.yield ();//comity}}}}public class Yielddemo {public static void main (String[]arg    s) {yield y = new Yield ();    New Thread (Y, "A"). Start ();  New Thread (Y, "C"). Start (); }}api Obsolete Method--easy to deadlock, it is not recommended to use STOP: the terminating thread immediately causes the thread to stop running and releases the lock held by the thread, which does not guarantee that the internal state of the object is correct; suspend: The suspended thread puts the thread into a "blocked" state in which the CPU does not divide the thread into a time slice. Entering this state can be used to suspend the operation of a thread, which is not available until the resume method is called. If you want to suspend the target thread to an importantsystem resources hold the lock, then no thread can use this resource until the target thread to be suspend is resumed. Resume: Recovery thread Recovery The thread that was suspended by the Suspend method Java2 started discarding the suspend () and resume () methods, because using these two methods could result in deadlocks, so you should call Wait () and notify () with the synchronization object Instead of suspend () and resume () for thread control. V. Thread security issues cause security problems: Multiple thread accesses are delayed. Thread randomness. Note: Thread safety issues are not easy to appear in the ideal state, but the impact on the software is very large. We can use the Thread.Sleep (long time) method to simply simulate the delay situation. Vi. thread synchronization When multiple threads access the same data, thread-safe issues are easy to see. Allow multiple operations to have only one thread in the same time period, and other threads to wait until the thread finishes before continuing. Classic case: The bank takes the money the user enters the withdrawal amount, the system determines whether the balance is greater than the withdrawal amount, the withdrawal succeeds, if the balance is less than the withdrawal amount, the withdrawal fails. Example analysis: Account field balance represents the balance to take money class: Drawmoney thread Class field A represents the account object, money represents the amount to be taken, and the withdraw behavior is placed inside the thread body; hint: public void run () {if (    C.getblance () >= money) {System.out.println (GetName () + ", take away" + 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); }}: When this happens, Java provides us with the synchronization code block synchronized (obj) {//obj represents the synchronization monitor, which is the same synchronization object/** ... TODO something*/} Method Two: Synchronized return value type method name (parameter list) {/** ..... TODO something*/} synchronization listener for synchronous methods actually, it's this/*.* * Accounts **/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.cur      Rentthread (). GetName () + ", remove" + Drawmoney);      try {thread.sleep (1);      } catch (Interruptedexception e) {e.printstacktrace ();      }//Modify Balance Setblance (Getblance ()-drawmoney);    System.out.println ("balance =" +getblance ());    }else{System.out.println ("Sorry for insufficient balance");  }}/*** Take the money Operation */public class Drawthread extendsthread{/*** Account * * Private accounts a;/*** take money * * public double Drawmoney;    Public Drawthread (String name,account a,double Drawmoney) {super (name);    THIS.A = A;  This.drawmoney = Drawmoney; }/*** When multiple threads modify the same shared resource data, it will cause data security issues */public void Run () {/* synchronized (a) {if (A.getblance () >= Drawmoney) {System.out.println (GetName () + ", remove" +drawmoney);        try {thread.sleep (1);        } catch (Interruptedexceptione) {e.printstacktrace ();        }//Modify Balance A.setblance (A.getblance ()-drawmoney);      System.out.println ("balance =" +a.getblance ());      }else{System.out.println ("Sorry for insufficient balance");  }}*/A.draw (Drawmoney); }} The above content is the class note after the homework today: to do a ticket booking process requires three windows, a total of 50 tickets, random ticket sales, after the sale of Xiao Ming in each window to buy tickets chance:

public class Dome {//main class
public static void Main (string[] args) {//Main method
Chuangkou C1 = new Chuangkou ("window One");
Chuangkou C2 = new Chuangkou ("window Two");
Chuangkou C3 = new Chuangkou ("window three");
thread T1 = new Thread (c1); Create a new three thread
Thread t2 = new Thread (c2);
thread t3 = new Thread (C3);
T1.start (); Three threads running at the same time
T2.start ();
T3.start ();
}
}

public class piao{//used to count votes
public static String name = "There is only one ticket at this time";
public static int piao = 1;
}

public class Chuangkou implements runnable{//window class
public String name;
static int a = 0; Define three static variables to count the total 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 advantageous for each window of the ticketing rate
} catch (Interruptedexception e) {
E.printstacktrace ();
}
Synchronized (piao.name) {//sync to prevent multiple threads from running at the same time
System.out.println (name+ "sold the first" +piao.piao+++ "Ticket");
}
Switch (name) {//Statistics window number of votes
Case "Window one": a+=1;break;
Case "Window two": B+=1;break;
Case "Window three": C+=1;break;
}
}
System.out.println (name+ "Sold out");
if (Piao.piao = = 50) {//Calculate the odds for Xiaoming to buy tickets
System.out.println ("Xiao Ming buys the window one ticket probability is" + (a/50.0));
System.out.println ("Xiao Ming buys window two ticket probability for" + (b/50.0));
System.out.println ("Xiao Ming buys window three ticket probability for" + (c/50.0));
}

}
}

At present, this homework still have problems, I do not know why Xiao Ming's efficiency sometimes appear two times, sometimes do not appear, I hope the great God guidance.

Threads (Java class notes)

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.