多线程同步问题请教

toodifficulttologin 2010-03-08 12:37:06
在孙鑫老师的视频中有一个售火车票的例子,如下:
public class TicketsSystem
{

public static SellTeckets sTeckets = new SellTeckets();
public static Thread thread1 = null;

public static void main(String[] args)
{

Thread thread = new Thread(sTeckets);
thread1 = new Thread(sTeckets);
thread.start();
thread1.start();

}
}

class SellTeckets implements Runnable
{
int tickets = 80;
Object object = new Object();
public void run()
{
while(true)
{
synchronized (object)
{
try
{
Thread.sleep(200);
}
catch (Exception e)
{
e.printStackTrace();
}
if(tickets > 0)
{
System.out.println(Thread.currentThread().getName() + ":" + tickets);
tickets --;
}
}

}
}
}
运行结果如下:
Thread-0:100
Thread-1:99
Thread-0:98
......
Thread-0:4
Thread-1:3
Thread-0:2
Thread-1:1
显示了Thread-0和Thread-1两个线程名,在同步操作tickets变量。

我另外写了一个类,在此类中利用TicketsSystem.sTeckets建立一个新的线程:
public class Test1
{
public static void main(String [] args)
{
System.out.println(TicketsSystem.thread1);
if(TicketsSystem.thread1 != null)
{
TicketsSystem.thread1.start();
}
}
}

之后我注释掉TicketsSystem类中的thread1.start();,然后先运行TicketsSystem,在TicketsSystem未结束前再启动Test1类结果显示:
TicketsSystem.thread1的值为null;

我的目的是测试两个类,同步操作tickets变量,模拟实际火车票的售票。
...全文
146 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
问题已解决,谢谢各位
  • 打赏
  • 举报
回复
可能上面的描述还是有点不清楚。
现在假若有一个java的火车标售票服务程序在运行,正在售K100车次的车票,怎么模拟多个客户端接入并售票的同步的例子??
  • 打赏
  • 举报
回复
在同一个类的main方法中产生多个线程,进行互斥这个我还是看懂了。

但是我的想法是类似于火车站售票,不同车站的客户端怎么对同一车次的车票进行同步?
这样,好象线程的启动不能放在一个类的main中吧?
chjh0540237 2010-03-08
  • 打赏
  • 举报
回复
线程同步:synchronized

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧