java-多线程并发编程:
重新学习下多线程并发编程
java基础:优先队列:PriorityQueue、数组赋值:System.arraycopy、二分搜索:Arrays.binarySearch
查看死锁(面试会问,比较好玩):
1. 命令行:jps
2. 查看堆栈:jstack pid
3. 可视化工具:jconsole
死锁的创建与命令使用:
import java.util.Arrays;
/**
* @ProjectName: test2
* @Package: PACKAGE_NAME
* @Description:
* @Author: huyuqiao
* @CreateDate: 2020/10/15 14:57
*/
public class test2 {
private static final Object A = new Object();
private static final Object B = new Object();
public static void main(String[] args){
/* String[] arr = {"A","B","C","D","E","F"};
System.arraycopy(arr, 3, arr, 0, 2);
Arrays.stream(arr).forEach(System.out::println);*/
/* int a[] = new int[] {1, 3, 3, 3, 4, 6, 8, 9};
System.out.println(Arrays.binarySearch(a, 1));*/
/* new Thread(() ->{
synchronized (A){
try{
Thread.sleep(3000);
} catch (Exception e){
e.printStackTrace();
}
synchronized (B){
System.out.println("线程A");
}
}
}).start();
new Thread(() -> {
synchronized (B){
synchronized (A){
System.out.println("线程B");
}
}
}).start();*/
}
}
线程创建:
-
继承Thread
/** * @ProjectName: MyThread * @Package: PACKAGE_NAME * @Description: * @Author: huyuqiao * @CreateDate: 2020/10/15 16:57 */ public class MyThread extends Thread { @Override public void run() { System.out.println("当前线程: " + Thread.currentThread().getName()); } public static void main(String[] args){ MyThread myThread = new MyThread(); myThread.setName("线程DEMO"); myThread.start(); } }
-
实现Runnable接口
/** * @ProjectName: MyRunnable * @Package: PACKAGE_NAME * @Description: * @Author: huyuqiao * @CreateDate: 2020/10/15 17:00 */ public class MyRunnable implements Runnable { @Override public void run() { System.out.println("当前线程名: " + Thread.currentThread().getName()); } public static void main(String[] args){ MyThread myThread = new MyThread(); myThread.setName("线程Runnable"); myThread.start(); myThread.run(); } }
-
匿名内部类
Thread thread = new Thread(new Runnable() { @Override public void run() { System.out.println("当前线程名:" + Thread.currentThread().getName()); } }); thread.start();
-
lambda表达式
public static void main(String[] args){ new Thread(()->{ System.out.println("当前线程名: " + Thread.currentThread().getName()); }).start(); }
-
线程池
public static void main(String[] args){ ExecutorService ex = Executors.newSingleThreadExecutor(); ex.execute(()->{ System.out.println("当前线程名;" + Thread.currentThread().getName()); }); }