ThreadTest.java 2.28 KB
Newer Older
shj committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

import org.junit.Test;

import java.util.Queue;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadTest {

    public static void main(String[] args) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                while (!isInterrupted()) {
                }
                System.out.println("finished");
            }
        };
        thread.start();
        thread.interrupt();
        System.out.println("hhh");
    }

    public static class Reentrant{
        private Lock lock=new ReentrantLock();
        private int inc=0;

        public int getInc() {
            return inc;
        }

        public void increment(){
            inc++;
        }
    }


    @Test
    public void ThreadPoolTest() throws InterruptedException {
        //CountDownLatch countDownLatch = new CountDownLatch(4);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2, 4, 1000, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(2));
        for (int i = 0; i < 4; i++) {
            executor.execute(()->{
                System.out.println("run..");
                //countDownLatch.countDown();
            });
        }
        //countDownLatch.await();
        System.out.println("END");
        executor.shutdown();

    }

    @Test
    public void InterruptTest() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                while (!isInterrupted()) {
                }
                System.out.println("finished");
            }
        };
        thread.start();
        thread.interrupt();
        System.out.println("hhh");
    }
}

class MyTask implements Runnable {
    private int taskNum;

    public MyTask(int taskNum) {
        this.taskNum = taskNum;
    }

    @Override
    public void run() {
        System.out.println("开始task " + taskNum);
        try {
            Thread.currentThread().sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("结束task " + taskNum);
    }

}

class MyThread extends Thread {

}