关于线程同步的问题测试 求解~!

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

该怎么解决呢?

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值