/*** Program is a static data process is a dynamic program thread is a continuous flow of control in a process * Program: CODE+DATA * Process: Program +CPU * Thread: Create + Ready + Run + block + Destroy * * 2 ways to generate thread classes * Inheritance: Java.lang. Thread+ object. Start (); * Implementation: Java.lang.runnable+ with the Thread class object. Start (); * 2 ways to rewrite run () * * Common method * Sleep (long time); * Active sleep yield (); * Voluntarily let the CPU join (); Immediately enter execution status * GetName (); SetName (); isAlive (); CurrentThread (); * Thread Priority: 1-10 default 5 10 Maximum * * Thread synchronization multiple threads access (operation) the same resource, which occurs concurrency phenomenon in order to ensure the rational and orderly utilization of shared resources, and create a synchronization mechanism * to achieve synchronization: through the main keywords synchronize and wait, Noti Mates for FY, etc. * WAIT (): Let the current thread object enter a wait state * Notify (): Let the current thread object emit a wake-up signal to let the waiting person wake up **/classStudentextendsThread {Private intscore; @Override Public synchronized voidrun () {Try{System.out.println ( This. GetName () + "Start exam ..."); Thread.Sleep (3000); System.out.println ("The exam is over and the quiz begins."); Thread.Sleep (3000); Score= (int) (Math.random () * 101); System.out.println ("The quiz is over, you can check your grades now."); This. Notify (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } Public synchronized intGetscore () {System.out.println (Thread.CurrentThread (). GetName ()+ "Please wait while exams and grading are in progress"); Try { This. Wait (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } returnscore; }} Public classThreadTest { Public Static voidMain (string[] args) {Student Student=NewStudent (); System.out.println ("Classmate you can test how many points?" "); System.out.println ("Give me some time, I'll take the exam, see"); Student.start (); System.out.println ("Check Student Exam results:" +Student.getscore ()); }}
Java Fundamentals-Threading