public class 多线程 {
static boolean flag = true;
static class t1 implements Runnable{
@Override
public void run() {
while (true){
Systrem.out.println("11");
}
}
}
public static void main(String[] args) throws IOException {
new Thread(new t1()).start();
}
}
public class 多线程 {
public static void main(String[] args) throws IOException {
new Thread(() -> {
...
}).start();
}
}
对 synchronized 的理解
1 控制变量时使用锁代码块
2 要注意锁代码块是放在循环里面还是外面
3 sleep不会释放锁 wait会释放资源4 我感觉锁对象是一个字符串比较好使 , 使用this 比较常
死锁
public class 死锁 { public static void main(String[] args) { new Thread(() -> { synchronized ("aaa"){ System.out.println("aaa等待bbb锁"); //为了防止第二个线程还未启动便将bbb锁执行完 for (int i = 0; i < 1000000; i++) { int k=0;k++; } synchronized ("bbb"){ System.out.println("aaa执行bbb"); } } }).start(); new Thread(() -> { synchronized ("bbb"){ System.out.println("bbb等待aaa锁"); synchronized ("aaa"){ } } }).start(); } }
线程握手
//线程握手的synchronized实现
//线程握手的write()和notify()实现
Original: https://www.cnblogs.com/cheng9999/p/11947598.html
Author: cheng_blog
Title: 多线程
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/622012/
转载文章受原作者版权保护。转载请注明原作者出处!