多线程会出现的问题
1)请你看看以下的代码有什么问题?
public class Sell extends Thread{
private static int ticket=100;
@Override
public void run(){
while(true){
if(ticket<=0)
System.out.println("停止卖");
break;
}
Thread.sleep(1000);
System.out.println("窗口"+Thread.currentThread().getName()+
"售出一个,剩余票数还有"+(--ticket));
}
}
Sell sell1=new Sell();
Sell sell2=new Sell();
Sell sell3=new Sell();
sell1.start();//启动三个线程
sell2.start();
sell3.start();
结果:多个线程共享ticket变量,会导致ticket的值变为-1甚至-2才停下来,而不是为0才停。
原因:没上锁,可能三个线程同时走进if分支。
2)请你看看以下的代码有什么问题?
public class Sell02 implements Runnable{
private int ticket=100;
@Override
public void run(){
while(true){
if(ticket<=0)
System.out.println("停止卖");
break;
}
Thread.sleep(1000);
System.out.println("窗口"+Thread.currentThread().getName()+
"售出一个,剩余票数还有"+(--ticket));
}
}
与1)的不同点:
- 继承类改为了实现接口
- 取消了static
此时把同个对象放到了不同线程。
Sell02 sell1=new Sell02();
new Thread(sell1).start();//启动三个线程
new Thread(sell1).start();
new Thread(sell1).start();
结果:还是会有负数现象。
原因:同1)。
那么此时怎么解决这个多线程的问题?
用线程同步技术Synchronized加在代码块中即可。