package thread;
/**
- 多线程并发安全问题
- 当多个线程并发操作同一临界资源时,由于线程切换时机不确定,导致代码执行顺序未按照设计顺序执行,
- 从而出现操作混乱,严重时可能导致系统瘫痪
- @author green
*/
public class SyncDemo1 {
public static void main(String[] args) {
Table table=new Table();
Thread t1=new Thread() {
public void run() {
while (true) {
int bean=table.getBean();
Thread.yield();
System.out.println(getName()+":"+bean);
}
}
};
Thread t2=new Thread() {
public void run() {
while (true) {
int bean=table.getBean();
Thread.yield();
System.out.println(getName()+":"+bean);
}
}
};
t1.start();
t2.start();
}
}
class Table{
private int beans=20;//桌子上有20个豆子
/*
* 当一个方法使用关键字synchronized修饰后,这个方法变为“同步方法”。
* 此时该方法不允许多个线程同时到方法内部执行代码
* 将多个线程并发操作同 一资源改为有先后顺序的同步执行九可以解诀多线程并发的安全问题了
*/
public synchronized int getBean() {
if (beans==0) {
throw new RuntimeException("豆子已經沒了");
}
//Thread.yield();//运行到这里发生线程切换
return beans--;
}
}
运行输出情况1:
Thread-0:20
Thread-1:19
Thread-0:18
Thread-1:17
Thread-0:16
Thread-1:15
Thread-0:14
Thread-1:13
Thread-0:12
Thread-1:11
Thread-0:10
Thread-1:9
Thread-0:8
Thread-1:7
Thread-0:6
Thread-1:5
Thread-0:4
Thread-1:3
Thread-0:2
Thread-1:1
Exception in thread “Thread-0” Exception in thread “Thread-1” java.lang.RuntimeException: 豆子已經沒了
at thread.Table.getBean(SyncDemo1.java:49)
at thread.SyncDemo1$2.run(SyncDemo1.java:27)
java.lang.RuntimeException: 豆子已經沒了
at thread.Table.getBean(SyncDemo1.java:49)
at thread.SyncDemo1$1.run(SyncDemo1.java:17)
运行输出情况2:
Thread-1:19
Thread-0:20
Thread-1:18
Thread-0:17
Thread-0:15
Thread-1:16
Thread-0:14
Thread-0:12
Thread-0:11
Thread-0:10
Thread-1:13
Thread-1:8
Thread-0:9
Thread-1:7
Thread-0:6
Thread-1:5
Thread-0:4
Thread-1:3
Thread-0:2
Thread-1:1
该怎么解决呢?