Multi-threading of start, stop, and other

Start a thread

1.Runnable is a logical Thread execution
logic 2.CallableFutureTask Thread is to be executed, but encapsulates the feature to get the results
thus: starting a thread of only one way: new Thread () start () ;.

Terminate the thread

1.stop (not recommended)

Sample code:

public class Demo_Stop {

    public static void main(String[] args) throws InterruptedException {
        MyThread thread = new MyThread();
        thread.start();

        // 休眠1秒,确保i变量自增成功
        Thread.sleep(1000);
        thread.stop();

        // 确保线程已经终止
        while (thread.isAlive()) {}
        // 输出结果
        thread.print();
    }
}

class MyThread extends Thread {
    private int i = 0, j = 0;

    @Override
    public void run() {
        synchronized (this) {
            ++i;
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ++j;
        }
        System.out.println("锁释放。。。");
    }

    public void print() {
        System.out.println("i=" + i + " j=" + j);
    }
}

Printout:
Here Insert Picture Description
output needed is J 0 = 0 = I;
STOP method does not guarantee the consistency of the data synchronization code blocks, the security thread appeared

2.interrupt

Sample code:

public static void main(String[] args) throws InterruptedException {
        Thread workThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    System.out.println("运行中");
                    try {
                        Thread.sleep(100L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        //将擦除掉的isInterrupted状态补上
                        Thread.currentThread().interrupt();
                    }
                }
            }
        });
        workThread.start();
        Thread.sleep(3000L);
        workThread.interrupt();
    }

important point:

1.interrupt method does not interrupt thread, but marked the interrupt flag

Sample code:

public static void main(String[] args) throws InterruptedException {

        //开启一个线程
        Thread testThread = new Thread(){
            @Override
            public void run() {
                while(true){
                    System.out.println("isInterrupted:" + Thread.currentThread().isInterrupted());
                    System.out.println("state:" + Thread.currentThread().getState());
                }
            }
        };

        testThread.start();
        Thread.sleep(2000);

        //调用interrupt方法,不会改变线程状态
        //并不会让线程退出,只是做了一个interrupt标记
        testThread.interrupt();
    }

Output Results:
Here Insert Picture Description
It can be seen in the second sleep2, isInterrupted status value from false to true.

2. If the thread calling wait (), wait (long) method, join (), join (long, int), join (long, int), sleep (long, int) or sleep (long, int) methods after, in WAITING, Timed Waiting state after the thread is called interrupt method, thread WAITING, Timed Waiting state will be cleared, and throw InterruptedException exception.

Sample code:

public static void main(String[] args) throws InterruptedException {
        Thread testThread = new Thread(){
            @Override
            public void run() {
                while (true){
                    try {
                        System.out.println("running...");
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        /*
                        当线程处于 Waiting、TimedWaiting状态,
                        执行interrupted方法后,会从Waiting、TimedWaiting中退出
                        并且isInterrupted=true的信号被擦除
                         */
                        System.out.println(Thread.currentThread().getState());
                        System.out.println("isInterrupted:" + Thread.currentThread().isInterrupted());
                    }
                }
            }
        };
        
        testThread.start();
        Thread.sleep(1000);
        testThread.interrupt();
    }

Print Results:
Here Insert Picture Description

3. If the target thread is blocked by I / O or in NIO Channel, likewise, I / O operation is interrupted or returns Laid
special outlier.

4.park () \ after parkNanos method execution, the thread is in the WAITING, Timed Waiting, will be awakened, but will not throw an exception, and there is a very strange happens.

Sample code:

public static void main(String[] args) throws InterruptedException {
        Thread testThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    LockSupport.park();
                    System.out.println("ing...");
                }
            }
        });
        
        testThread.start();

        Thread.sleep(1000L);
        testThread.interrupt();

        System.out.println("============end=============================");

    }

Print results
Here Insert Picture Description

deamon thread

definition:

Daemon thread
refers to the provision of a universal service program runs in the background thread,
at the end of the process, it will kill all daemon threads.

important point:

1. Generate a new thread in the thread Daemon Daemon is also
2. General can not set the thread running as a daemon thread, thread.setDaemon (true) must be set before the thread.start (), otherwise it will run out of a IllegalThreadStateException abnormal .
3. daemon thread it will even happen in the middle of an operation interrupted at any time, so you should never ceases to access the natural resources, such as files, databases, etc.

CountDownLatch countdown

effect:

countDownLatch can make a thread wait for another thread is finished before their execution.

Sample code:

public class Demo_CountDownLatch {

    static AtomicLong num = new AtomicLong(0);

    public static void main(String args[]) throws InterruptedException {

        CountDownLatch ctl = new CountDownLatch(10);

        for (int i=0; i< 10; i++){
            new Thread(){
                @Override
                public void run() {
                    for (int j=0; j< 1000; j++){
                        num.getAndIncrement();
                    }
                    ctl.countDown();
                }
            }.start();
        }

        //设置开关,设置门栓
        ctl.await();
        System.out.println(num.get());
    }
}

Semaphore counting semaphores

effect:

The number of threads may be used to limit access to certain resources (physical or logical).
A method for concurrency control is shared lock.

Sample code:

public class Demo_Semaphore {

    public static void main(String args[]){

        Semaphore sp = new Semaphore(10);

        //短时间发送1000个请求,并发会很高,数据库会受不了
        for (int i=0; i<1000; i++){
            new Thread(){
                @Override
                public void run() {
                    try {
                        sp.acquire();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    //模拟DB查询
                    queryDb("localhost:3306");
                    sp.release();
                }
            }.start();
        }

    }
    //发送一个HTTP请求
    public static void queryDb(String uri)  {
        System.out.println("query===>: " + uri);
        // 类似sleep的作用
        LockSupport.parkNanos(1000 * 1000 * 1000);
    }
}

CyclicBarrier cycle fence

effect:

Can be recycled barrier

Sample code:

public class Demo_CyclicBarrier {
    public static void main(String[] args) {

        CyclicBarrier barrier  = new CyclicBarrier(5,// 栅栏一次通过的请求数
                new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(">>> 这是一个栅栏。。。");
                    }
                });

        //传入一个Runnable,打印栅栏
        for (int i=0; i< 100; i++){
            new Thread(){
                @Override
                public void run() {
                    try {
                        barrier.await();    //
                        System.out.println("请求...");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
            LockSupport.parkNanos(1000 * 1000 * 1000L);
        }
    }
}
Published 53 original articles · won praise 42 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_42815122/article/details/104412351