public class ThreadDemo implements Runnable{
//票的总数
private int ticket=10;
public synchronized void sale()
{
if(ticket>0)
{
System.out.println(Thread.currentThread().getName()+"号窗口卖出"+this.ticket--+"号票");
}
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=1;i<50;i++)
{
try {
//休眠1s秒中,为了使效果更明显,否则可能出不了效果
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.sale();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t1 = new Thread(new ThreadDemo());
t1.setName("线程1");
Thread t2 = new Thread(new ThreadDemo());
t2.setName("线程2");
t1.start();
t2.start();
}
}
为什么同步不了
------解决思路----------------------
main方法应该修改为
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadDemo td = new ThreadDemo()
Thread t1 = new Thread(td);
t1.setName("线程1");
Thread t2 = new Thread(td);
t2.setName("线程2");
t1.start();
t2.start();
}
你的代码写的两个线程根本没有共享数据,还同步个啥?
------解决思路----------------------
两个线程对象操作自己的对象,怎么可能同步呢