java线程

1.创建线程

public class TestThread {
    public static void main(String[] args) {
        Thread1 thread1 = new Thread1();
        thread1.start();

        Thread thread2 = new Thread(new Thread2());
        thread2.start();
    }
}
class Thread1 extends Thread {
    @Override
    public void run() {
        System.out.println("方式1:继承Thread类");
    }
}
class Thread2 implements Runnable {
    @Override
    public void run() {
        System.out.println("方式2:实现Runnable接口");
    }
}
public class Callable01 implements Callable<String> {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask task = new FutureTask(new Callable01());
        new Thread(task).start();
        System.out.println(task.get());//内部自旋阻塞
    }

    @Override
    public String call() throws Exception {
        return "方式3:实现Callable泛型接口";
    }
}

2.线程状态

new 初始状态
runnable 运行状态,就绪和运行中
blocked 阻塞状态 synchronized
waiting 等待,需要其他线程做出一些特定动作 wait/notify、join
time_waiting 超时等待,可以在指定的时间自行返回,sleep、join
terminated 终止状态

public class ThreadState {
    public static void main(String[] args) {
        new Thread(new TimeWaiting(), "TimeWaitingThread").start();
        new Thread(new Waiting(), "WaitingThread").start();
        new Thread(new Blocked(), "BlockedThread-1").start();
        new Thread(new Blocked(), "BlockedThread-2").start();
    }

    static class TimeWaiting implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class Waiting implements Runnable {
        @Override
        public void run() {
            while (true) {
                synchronized (Waiting.class) {
                    try {
                        Waiting.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    static class Blocked implements Runnable {
        @Override
        public void run() {
            synchronized (Blocked.class) {
                while (true) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

3.线程执行顺序(join)

public class ThreadSort {
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread1");
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread2");
            }
        });
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread3");
            }
        });

        thread1.start();
        thread1.join();
        thread2.start();
        thread2.join();
        thread3.start();
        thread3.join();
    }
}

4.线程池

线程和线程池比较,这里线程池比线程性能高了10倍左右

public class TestThreadPool {
    public static void main(String[] args) throws InterruptedException {
        Long start = System.currentTimeMillis();
        final List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            final int j = i;
            Thread thread = new Thread() {
                @Override
                public void run() {
                    list.add(j);
                }
            };
            thread.start();
            thread.join();//主线程等待子线程结束
        }
        System.out.println(System.currentTimeMillis() - start);
        System.out.println(list.size());//1800
    }

    public static void main2(String[] args) throws InterruptedException {
        Long start = System.currentTimeMillis();
        final List<Integer> list = new ArrayList<>();
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10000; i++) {
            final int j = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    list.add(j);
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.DAYS);//主线程等待子线程1天
        System.out.println(System.currentTimeMillis() - start);
        System.out.println(list.size());//20
    }
}

5.线程池种类

  • 普通线程池
  • 定时线程池

6.volatile

线程间变量可见性

public class App {
    public static void main(String[] args) throws InterruptedException {
        Test test = new Test();
        new Thread(() -> {
            test.doWork();
        }).start();
        Thread.sleep(1000);
        new Thread(() -> {
            test.shutDown();
        }).start();
    }
}

class Test {
    volatile boolean _shutDown = false;

    public void doWork() {
        while (!_shutDown) {
            //中间没有时间间隔的情况下,无法获取_shutDown变更后的值
            /*try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
            //System.out.println("执行中。。。");
        }
        System.out.println("系统被关闭了");
    }

    public void shutDown() {
        _shutDown = true;
    }
}

7.ReentrantLock(手动锁)

常用方法:

  • lock 获得锁
  • unlock 释放锁
  • tryLock(long timeout, TimeUnit unit) 等待获得锁
  • lockInterruptibly() 中断锁
public class TestLock {
    public static void main(String[] args) {
        Test1 test1 = new Test1();
        new Thread(() -> {
            test1.test();
        }, "thread-1").start();
        new Thread(() -> {
            test1.test();
        }, "thread-2").start();
    }
}

class Test1 {
    ReentrantLock lock = new ReentrantLock();

    public void test() {
        try {
            if (lock.tryLock(5, TimeUnit.SECONDS)) {
                System.out.println(Thread.currentThread().getName() + "获得锁");
                try {
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } finally {
                    lock.unlock();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
原文地址:https://www.cnblogs.com/yinchh/p/12451916.html