Callable和Runnable接口实现多线程
lambda表达式解析:
匿名内部类:
Java内部类和匿名内部类的用法_pan_jinquan的博客-CSDN博客_内部类和匿名内部类
lambda表达式:
Java中Lambda表达式的使用_weixin_39407066的博客-CSDN博客_lambda表达式java
线程优先级:
多线程同步问题和处理:
package hxw.io;
/**
* @Description:
* @Author: huangxunwei
* @Date: 2022/3/23 15:57
* 同步问题
*/
public class demo323 {
public static int ticket=5;
public static void main(String[] args) {
Runnable body=()->{
while (true){
if(ticket>0){
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("【"+Thread.currentThread().getName()+"售票,还剩"+(--ticket));
}else {
break;
}
}
};
for (int x=0;x<5;x++){
new Thread(body,"票贩子:"+x).start();
}
}
}
执行结果:
【票贩子:2售票,还剩4
【票贩子:0售票,还剩1
【票贩子:4售票,还剩2
【票贩子:3售票,还剩3
【票贩子:1售票,还剩3
【票贩子:0售票,还剩-1
【票贩子:1售票,还剩0
【票贩子:4售票,还剩-2
【票贩子:2售票,还剩-4
【票贩子:3售票,还剩-3
Process finished with exit code 0
同步处理:
通过“synchronized (this) {}” 同步代码块 实现同步处理
public class demo323 {
public static int ticket=5;
public static void main(String[] args) {
demo323 demo323=new demo323();
Runnable body=()->{
while (true) {
synchronized (demo323) {
if (ticket > 0) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("【" + Thread.currentThread().getName() + "售票,还剩" + (--ticket));
} else {
break;
}
}
}
};
for (int x=0;x<5;x++){
new Thread(body,"票贩子:"+x).start();
}
}
}
优化代码:
class TicketBody implements Runnable{
private int ticket=5;
@Override
public void run() {
while (true) {
synchronized (this) {
if (ticket > 0) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("【" + Thread.currentThread().getName() + "售票,还剩" + (--ticket));
} else {
break;
}
}
}
}
}
public class demo323 {
public static void main(String[] args) {
TicketBody body=new TicketBody();
for (int x=0;x<5;x++){
new Thread(body,"票贩子:"+x).start();
}
}
}
执行结果:
【票贩子:0售票,还剩4
【票贩子:0售票,还剩3
【票贩子:0售票,还剩2
【票贩子:0售票,还剩1
【票贩子:0售票,还剩0
通过同步方法实现同步处理:
public class demo323 {
public static int ticket=5;
public static void main(String[] args) {
demo323 demo323=new demo323();
Runnable body=()->{
while (sale()) {
;
}
};
for (int x=0;x<5;x++){
new Thread(body,"票贩子:"+x).start();
}
}
public static synchronized boolean sale(){
if (ticket > 0) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("【" + Thread.currentThread().getName() + "售票,还剩" + (--ticket));
return true;
} else {
return false;
}
}
}
【票贩子:0售票,还剩4
【票贩子:0售票,还剩3
【票贩子:0售票,还剩2
【票贩子:0售票,还剩1
【票贩子:0售票,还剩0