java study notes ---- simple multi-threaded implementation code and interrupt threads

Why use multithreading?

    1. perform multiple tasks simultaneously

    2. The need for other operations to perform certain complex tasks

    

Easy way to perform a task in a separate thread:

 1. Construction of a class that implements Runnable interface:

class MyRunnable implements Runnable{
public void run(){
    //在这里写任务代码
}
}

2. Create an instance of the class:

Runnable r =new MyRunnable();

3. Create a Thread object from the Runnable:

Thread t = new Thread(r);

4. Start threads:

t.start();

Not required to implement Runnable interface implementation:

class MyThread extends Thread{
    public void run(){
        //任务代码
}
}

note:

Will perform tasks in the same thread when calling Thread or Runnable object's run method will not start a new thread.

 

Thread interrupts:

stop and suspend have been abandoned.

Thread interrupt status: each thread has a such a boolean flag to indicate whether the thread is interrupted from time to time each thread should check the status to determine whether the thread is interrupted.

The method of using the interrupt request to terminate the thread, which will interrupt status bit is set

Determine whether the current thread's interrupt thread is set:

while(!Thread.currentThread().isInterrupted()){
    //Thread.currentThread()用以获得当前线程
}

When a thread is blocked and can not detect interrupt status, will produce abnormal InterruptedException

If you call sleep method is set in the interrupt status, it does not sleep. Instead, it is clear that the state and throw InterruptedException

note:

Do not ignore the exception, the thread can be interrupted by capture or simply become abnormal after Thrown (throws) instead of using the catch

 

Reference: "java core technology Ⅰ"

Guess you like

Origin blog.csdn.net/weixin_42486701/article/details/93408333