The basic analytical thread

Thread object is an object can produce thread. For example, in the Java the Thread objects platform, Runnable object. Thread, correction is made in a sequence of execution pointing. On the java platform is starting from the start a thread object (), run run method body that a relatively independent processes. Compared to multi-process, multi-threaded advantages are:

    You can not share data between (1) a process, a thread can;

    (2) The system creates a process to re-allocate system resources required for the process, so the cost of creating a thread is relatively small;

    (3) Java language built-in support for multi-threading capabilities, simplifying the java multithreaded programming.

First, create a thread and start

  (1) Create a thread class inheritance Thread class

By inheriting concrete steps and specific code Thread class Thread class is created as follows:

   • Define a subclass inherits the Thread class, the class and override run () method;

   • Create an instance of a subclass of Thread that created thread object;

   • call the thread object's start () method to start a thread.

class SomeThead the extends Thraad { 
     public  void RUN () { 
      // method to override 
    }   
 } 
 
public  static  void main (String [] args) { 
 SomeThread oneThread = new new SomeThread ();    
  Step 3: Thread Start:    
 oneThread.start () ; 
}

 

(2) implement Runnable interface to create thread class

Through specific steps and specific code implementation Runnable interface created thread class is as follows:

   • defined class that implements Runnable interface, the interface and override run () method;

   • Create an instance of Runnable implementation class and use it as an example of Thread of the target object, that is, the Thread object is the real thread object.

class SomeRunnable implements Runnable   { 
  public void run()   { 
  //所要重写的方法 
  }  
} 
Runnable oneRunnable = new SomeRunnable();   
Thread oneThread = new Thread(oneRunnable);   
oneThread.start();

The above two methods can achieve the creation of the Thread class

However, the devil of a time to start at first glance seem to feel substantially no difference, but it apparently is not so simple, I ask, when Thread time if demand requires inherit other class, that can extend inheritance the parent domain, it is not just in case you want to inherit a parent does, Thread, after all, just a class, not an interface, eh! ! By the way, this time with a Runnable will be a lot easier, we summarize below it is the correlation of Runnable and Thread.

 

**** Runnable and Thread difference and contact? ****

1) Thread is a class, Runnable is an interface;

2) Thread class implements Runnable interface, override the run method.

3) Runnable is an interface, while the definition of a class that implements the interface can also inherit from other classes; Runnable support multiple inheritance wording;

4) Runable can simply sharing data; Thread to achieve very good; in fact be achieved

5) Runnable multiple threads for the same program code to process the same resources, to avoid the limitations of single inheritance in Java, increasing process robustness, code can be shared by multiple threads, separate code and data. Thread pool can only achieve Runnable class into the thread, not directly into the inheritance Thread class.

 

In the interview, many hiring managers like to ask some questions about the state of the thread, perhaps not ask particularly fine, but at least we have to say the truth out, below is the thread of life cycle, it is common to pick a few explain, in fact, some of my own induction, there are some online dd down, understand what is truth, organize their own set of vernacular best.

  • New threads:
    •  After establishing a thread object and using new Thread class or subclass, the thread object is nascent state. Thread nascent state has its own memory space, enter the ready state (runnable) by calling the start method, it exists only as an object instance, JVM no CPU time slice and other threads running resources assigned;.

      Note: can not thread has been started calling start () method again, there would be the Java .lang.IllegalThreadStateException abnormal.

       

  • Ready state:
    • Calling thread is created in the state of start method to convert the state of the thread to the ready state (albeit using a queue forms, in fact, called it runs the pool rather than run queue because the cpu scheduling necessarily to advanced prior to the scheduled order). Wait for the system to assign CPU. The state is not waiting execution state, when the system is waiting for a Thread object is selected executed, it will enter the execution state from the waiting to be executed, the system selected action called "cpu scheduling." Once the CPU, thread enters running state and automatically call their own run method
    • Tip : If you want to run immediately after sub-thread calls start () method, you can use Thread.sleep () mode so that the main thread to sleep for a Huoer, turn to execute child thread. (SLEEP () method will be explained below)

       

  • Operating status :
    • Thread running is the most complex, there is blocking state, readiness and state of death
    • Thread in the ready state, if obtained cpu scheduling, will run from the ready state to state, execution run () method in the task. If the thread is lost cpu resources, it will run and from the state to the ready state. Re-allocation of resources to wait for the system. You can also call the state of threads running yield () method, it will make the cpu resources, become ready again. ( ** thread when a thread calls yield () method after a pause, the current thread with the same priority or higher priority than the current thread's state of readiness are more likely to get a chance to execute, of course, just possible, because we can not interfere with an accurate cpu scheduling threads.)
  • Wait / blocked:
    • Blocked here I can not say, because I have not seen through (spurting), I can understand that when one thread occupy CPU run by another thread or suspended sentence or deprivation of the right to use it, so blocking state.
    • Thread blocking state can not enter the ready queue. Only when the cause of obstruction of elimination, such as sleep time is up, or wait for the I / O device idle down, the thread into the ready state, again into the ready queue waiting in line, after being selected from the original system stopped position continue to run.

 

 

 

Java provides a convenient way to control the number of threads for the state, it is common to name a few examples, I would not be much. details as follows:

1, thread sleep --sleep

      If we need to pause the currently executing thread for some time, and enter the blocked state, you can call sleep method of the Thread by.

Note:

   (1)sleep是静态方法,最好不要用Thread的实例对象调用它,因为它睡眠的始终是当前正在运行的线程,而不是调用它的线程对象,它只对正在运行状态的线程对象有效。如下面的例子:

 1 package day7_3HomeWork;
 2 
 3 public class Thread_text {
 4 
 5     public static void main(String[] args) {
 6         Thread_input ti = new Thread_input();
 7         ti.start();
 8 
 9     }
10 }
11 class Thread_input extends Thread{
12     String[] str = {"我","我爱","我爱福","我爱福建","我爱福建工","我爱福建工程","我爱福建工程学","我爱福建工程学院"};
13     @Override
14     public void run() {
15         // TODO Auto-generated method stub
16         for(int i=0;i<str.length;i++)
17         {
18             System.out.println(str[i]);
19             try {
20                 sleep(2000);
21             } catch (InterruptedException e) {
22                 // TODO Auto-generated catch block
23                 e.printStackTrace();
24             }
25         }    
26     }
27 }

Equivalent to just suspend the current process is running, the thread is blocked, 2000mills at the end of the sleep time to change back to a ready state, and ready to run into the state, is controlled by the system, we can not accurate to interfere it is, so if you call Thread.sleep (1000) makes the thread to sleep for one second, the result may be greater than 1 second. The figure is a method of sleep, is the need to pass a long mills parameter, which is a unit of milliseconds.

(2) Java thread scheduling is a core multi-threaded Java, only good schedule, in order to maximize the performance of the system and improve the performance of programs. But no matter how programmers write scheduling, can only maximize the impact of threads of execution order, but can not do precise control.

 

Guess you like

Origin www.cnblogs.com/wudidamowang666/p/11130012.html