State and create a thread thread

One: Create a multithreaded

Method One : Thread class inheritance
can be created by a thread inheritance Thread class, the benefits of this approach is that this is representative of the current thread does not need to pass
to get a reference to the current thread Thread.currentThread ().

class MyThread extends Thread {
  @Override
  public void run() {
    System.out.println("这里是线程运行的代码");
 }
}
MyThread t = new MyThread();
t.start(); // 线程开始运行

Method Two : Implement Runnable interface
by implementing Runnable interface, and call the constructor of the Thread Runnable object as a target parameter passed to create a thread object. The advantage of this method is that you can circumvent the limitations of single class inheritance; but need to get the current thread referenced by Thread.currentThread ()

class MyRunnable implements Runnable {
  @Override
  public void run() {
    System.out.println(Thread.currentThread().getName() + "这里是线程运行的代码");
 }
}
Thread t = new Thread(new MyRunnable());
t.start(); // 线程开始运行

II: state of the thread

And Reference: https: //blog.csdn.net/RookiexiaoMu_a/article/details/88625960 ops_request_misc =% 7B % 22request_id% 22% 3A% 22158189170219725247642062% 22% 2C% 22scm% 22% 3A% 2220140713.130056874 ...% 22% 7D & request_id? 158189170219725247642062 & biz_id = 0 = & utm_source = distribute.pc_search_result.none-Task
Here Insert Picture Description
NEW : thread object objects just created, executed before () start.
RUNNABLE : threads can run in a state of java virtual machine, you may be running their own codes, or may not, depending on the operating system processor
BLOCKED : When a thread tries to acquire an object lock, and the object lock is held by another thread there, the thread enters the Blocked state; when the thread holding the lock, the thread will become Runnable state.
The WAITING : a thread when another thread is waiting to perform a (wake-up) action, the thread enters the Waiting state. After entering this state it is not automatically wake up, have to wait for another thread to notify or notifyAll transfer method to be able to wake up.
TIMED_WAITING : with waiting state, there are several methods timeout parameters, they will enter TimedWaiting call status. This state will be maintained until the timeout expires or receives a wake-up notification. Common method with a timeout parameter are Thread.sleep, Object.wait.
TERMINATED: Because the run method exits normally and death, or because there is no capture of aborted the run method and death

Published 46 original articles · won praise 2 · Views 1875

Guess you like

Origin blog.csdn.net/zhanghongkai0916/article/details/104383207