Java-多线程并发编程
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()); }); }
我曾七次鄙视自己的灵魂:
第一次,当它本可进取时,却故作谦卑;
第二次,当它在空虚时,用爱欲来填充;
第三次,在困难和容易之间,它选择了容易;
第四次,它犯了错,却借由别人也会犯错来宽慰自己;
第五次,它自由软弱,却把它认为是生命的坚韧;
第六次,当它鄙夷一张丑恶的嘴脸时,却不知那正是自己面具中的一副;
第七次,它侧身于生活的污泥中,虽不甘心,却又畏首畏尾。