当前位置: 代码迷 >> J2SE >> 进程 同步有关问题
  详细解决方案

进程 同步有关问题

热度:393   发布时间:2016-04-23 22:10:32.0
进程 同步问题
class MyThread implements Runnable{
private int ticket=10;
public void run(){
synchronized(this){
for(int i=0;i<100;i++){
if(ticket>0){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"卖掉第"+ticket--+"张票");
}
}
}
}
}
public class SynchronizedDemo{
public static void main(String args[]){
MyThread mt=new MyThread();
Thread t1=new Thread(mt,"窗口1");
Thread t2=new Thread(mt,"窗口2");
Thread t3=new Thread(mt,"窗口3");
t1.start();
t2.start();
t3.start();
}
}

为什么只有一个窗口买票,而不是三个窗口同时买票,求大神分析一下
线程 同步

------解决方案--------------------
下面是我修改后的代码,希望对你有帮助:

package zhangming.csdn;

class MyThread implements Runnable
{
private int ticket=10;
public void run()
{

for(int i=0;i<10;i++) //建议不要将i的最大值设的太大这样太浪费资源
{
//先睡眠,后锁定,以便让其他线程进来
try
{
Thread.sleep(1000);
}catch(InterruptedException e){e.printStackTrace();}
//在进行售票时,需要进行锁定
synchronized(this)
{
if(ticket>0)
{
System.out.println(Thread.currentThread().getName()+"卖掉第"+ticket--+"张票");
}
}
}
}
}
public class SynchronizedDemo
{
public static void main(String args[])
{
MyThread mt=new MyThread();
Thread t1=new Thread(mt,"窗口1");
Thread t2=new Thread(mt,"窗口2");
Thread t3=new Thread(mt,"窗口3");
t1.start();
t2.start();
t3.start();
}
}

------解决方案--------------------
仅供参考:

class MyThread implements Runnable {
private int ticket = 10;

public void run() {
while (ticket > 0) {//循环条件
  相关解决方案