多线程出现目的
如何使用多线程
线程状态(6种)
线程开启/停止
线程安全
Volilate
Sychronized
机制
如何实现锁
为什么任何一个对象都可以成为锁
锁的优化
Lock与Synchronized区别
CAS
AQS(AbstractQueuedSychronizer)
ReentrantLock
Lock()加锁分析
unlock()释放锁分析
CountDownLatch
是什么
如何使用
分析
多线程出现目的
场景:
当一个进程处理过程中,遇到网络与IO操作都会进入阻塞状态,不再处理任何东西,浪费系统资源。
一个函数的处理非常耗时,其实其中多个逻辑可以并行处理。
多线程的面世就是要解决以上问题。
如何使用多线程
extends Thread
public class ThreadDemo extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":" + "ThreadDemo Running");
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new ThreadDemo().start();
}
}
}
implements Runnable
public class RunnableDemo implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":" + "RunnableDemo Running");
}
public static void main(String[] args) {
RunnableDemo runnableDemo = new RunnableDemo();
for (int i = 0; i < 10; i++) {
new Thread(runnableDemo).start();
}
}
}
ExecutorService
Executors.newFixedThreadPool
Executors.newCachedThreadPool
Executors.newSingleThreadPool
Executors.newScheduledThreadPool
public class ExecutorServiceDemo {
private static ThreadPoolExecutor threadPool;
private static ThreadFactory factory = new ThreadFactory() {
private final AtomicInteger integer = new AtomicInteger();
@Override
public Thread newThread(Runnable r) {
int threadName = integer.getAndIncrement();
System.out.println("Created Thread:" + threadName);
return new Thread(r, "ThreadPool Thread:" + threadName);
}
};
private static BlockingQueue workQueue = new ArrayBlockingQueue(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(1);
threadPool = new ThreadPoolExecutor(10, 15, 1000L,
TimeUnit.SECONDS,
workQueue,
factory);
//execute()与submit()的区别在于submit有一个Future类型的返回,
// 实际submit是把Callable入参包装成RunnableFuture类型后再调用execute();
for (int i = 0; i < 15; i++) {
System.out.println("threadPool.execute");
threadPool.execute(new RunnableDemo());
}
for (int i = 0; i < 15; i++) {
System.out.println("threadPool.submit");
Future> future = threadPool.submit(new CallableDemo());
System.out.println(future.get());
}
}
}
implements Callable<>
public class CallableDemo implements Callable {
@Override
public String call() throws Exception {
System.out.println(Thread.currentThread().getName() + ":" +"CallableDemo Running");
return "Callable Result";
}
public static void main(String[] args) throws Exception {
CallableDemo callableDemo = new CallableDemo();
String callableReturn = callableDemo.call();
System.out.println("callableReturn :" + callableReturn);
}
}
Callable与Runable区别:
Re:
Callable任务线程能返回执行结果,而Runnable任务线程不能返回结果
Callable能向上抛出异常,而Runnable接口异常只能内部消化
为什么提供extends Thread又提供implements Runnable
Re:因为JAVA不支持多继承
线程状态(6种)
image.png
NEW 调用Start方法前
RUNNABLE 运行
BLOCKED 阻塞
等待阻塞 wait
同步阻塞 synchronized
其它阻塞 sleep/join
WAITING 等待
TIMED_WAITING 超时等待
TERMINATED 终止
状态变更图示: