Java并发相关知识点总结
线程基础
创建线程的方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class MyThread extends Thread { @Override public void run() {} }
class MyRunnable implements Runnable { @Override public void run() {} }
class MyCallable implements Callable<String> { @Override public String call() throws Exception { return "result"; } }
|
线程状态
- NEW:新建
- RUNNABLE:运行
- BLOCKED:阻塞
- WAITING:等待
- TIMED_WAITING:超时等待
- TERMINATED:终止
synchronized关键字
1 2 3 4 5 6 7 8 9 10
| public synchronized void method() {}
public void method() { synchronized(this) {} }
public static synchronized void staticMethod() {}
|
volatile关键字
1
| volatile boolean flag = true;
|
ThreadLocal
1 2 3 4
| ThreadLocal<String> tl = new ThreadLocal<>(); tl.set("value"); String value = tl.get(); tl.remove();
|
线程池
1 2 3 4
| ExecutorService executor = Executors.newFixedThreadPool(10); executor.execute(() -> {}); executor.submit(() -> {}); executor.shutdown();
|
总结
并发编程需要理解线程、锁、volatile、线程池等核心概念,合理使用才能写出高效安全的多线程代码。