Home > Java > javaTutorial > java thread

java thread

伊谢尔伦
Release: 2016-12-10 09:50:44
Original
1230 people have browsed it

1. Writing multi-threaded programs in Java is much easier than other programming languages. Mainly implemented through Runnable interface and Thread class.

publicclassSimpleRunnable implements Runnable{
   private String message;
   publicstaticvoid main(String[] args) {
      SimpleRunnabler1 = new SimpleRunnable("Hello");
      Threadt1 = new Thread(r1);
      t1.start();
      for(;;){
         System.out.println("Bye-bye");
      }
   }
   public SimpleRunnable(String message){
      this.message = message;
   }
   @Override
   publicvoid run() {
      for(;;){
         System.out.println(message);
      }
   }
}
Copy after login

Above, multi-threading is implemented by inheriting the Runable interface to implement run(), and Thread is used to implement the virtual CPU, allowing thread r1 to run in an independent thread. In fact, this thread and the main thread are not completely independent threads. Instead, the r1 thread and the main thread switch and run in turns. However, the switching speed is very fast, and it looks like two threads running independently.

2. Thread switching varies according to different operating systems:

One is the queuing mechanism. If a thread grabs the CPU, it will not be launched until the thread finishes running or is passively stopped.

One is through the priority mode, the thread with the highest priority gets the CPU first.

One is time slice. Each thread has a fair time slice. When a thread exits after running the time slice, other threads have a fair chance to seize the CPU.

Java's threads adopt a comprehensive approach based on priority and time slices. The specific implementation varies depending on the operating system it is running on. For example, when a thread finishes running its time slice, it exits and lowers its priority by one level, and then the thread with a higher priority is sorted to seize the CPU. If a thread with a higher priority comes during the running process, it will seize the current one. CPU.

3, Thread running status:

Thread stop (Pause) includes, sleep(), wait(), suspend(), I/O blocking

Thread restart (Run) includes, sleep time-out, notify() , resume(), I/O finished

Thread terminated, stop()

Thread waiting, join()

Thread actively gives up CPU, yield()

Above suspend(), resume(), stop() All are obsolete and no longer recommended.

4, The sleep() function is static and is a function belonging to a class, not an object. This function will cause the calling thread to pause for a certain period of time, rather than stopping some other thread. As follows

publicstaticvoidmain(String[] args)throwsException {
      SimpleRunnabler1 = new SimpleRunnable("Hello");
      Threadt1 = newThread(r1);
      t1.start();
      for(inti = 0; i < 10; i++){
         System.out.println("Bye-bye");
      }
      t1.sleep(10000);
      t1.stop();
}
Copy after login

The above code stops the main thread for 10 seconds instead of stopping t1 for 10 seconds. In addition, the time that sleep() causes the thread to pause is a fuzzy value. The above theory will cause the main thread to pause for 10 seconds. However, due to the uncertainty of thread switching, the main thread does not pause for exactly 10 seconds.

5. Another static function is yield(), which means that the currently running thread actively gives up the CPU. This function can only act on the current thread, similar to the sleep() function above.

6. Programming is to pursue efficient results and use multi-threading. However, multi-threaded operation is difficult to predict, so we will take certain methods to make the results of multi-threaded operation as predictable as possible.

class Thread1 extends Thread{
   @Override
   publicvoid run(){
      try{
         System.out.println("thread1 start");
         sleep(10000);                  // <3>
         System.out.println("thread1 finish");//<4>
      }catch(Exception e){
      }
   }
}
class Thread2 extends Thread{
   @Override
   publicvoid run(){
      try{
         System.out.println("thread2 start");
         suspend();                  // <2>
         System.out.println("thread2 finish");// <7>
      }catch(Exception e){
      }
   }
}
publicclassThreadTest {
 
   publicstaticvoid main(String[] args) {
      Threadt1 = new Thread1();
      Thread2t2 = new Thread2();
      t1.start();
      t2.start();
      try{
         System.out.println("s1");
         t1.join();                  // <1>
         System.out.println("s2");      // <5>
         t2.resume();                //<6>
         System.out.println("s3");      // <8>
         t2.join();                  // <9>
      }catch(Exception e){
      }
      System.out.println("s4");         // <10>
   }
}
Copy after login
运 or above running the one -time running result is:

Thread1 Start

Thread2 Start

s1

Thread1 Finishh

s2

s3

Thread2 Finishh

s4

, but not every time I get this way the result of. But some of it is predictable. Which ones are predictable? Which ones are unpredictable?

(1) The first three lines will definitely occupy the first three lines. Since the code of <1> stops the main thread and waits for the end of thread t1, the t1 thread pauses the thread for 10 seconds at <3>. The code at <2> indicates that thread t2 is in a suspended state. Until there is code to wake up the thread, otherwise the thread will remain blocked. But the output order of the first three lines is unpredictable.

(2) The fourth line will definitely be on the fourth line. When t1 sleep ends, run the code at <4> first.

(3) The fifth line will definitely be on the fifth line. When the t1 thread ends, the main The thread gets the CPU and starts running the code <5>

(4) The positions of the sixth and seventh lines may be interchanged. When the code <6> wakes up thread t2, it starts running from <7>, and at the same time the main thread Continue to run <8>

(5) The last line will definitely be the last line. Pause the main thread at <9>, wait for the completion of t2, run <10> to output the last line, and the main thread ends and exits.


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template