把其中的一个线程sleep的时间设为1就是另外一个结果了,大于1就可以了,为什么呢?class ThreadDemo6
{
public static void main(String [] args)
{
ThreadTest t=new ThreadTest();
new Thread(t).start();
try{Thread.sleep(2); //就是此处
}
catch(Exception e){
}
t.str=new String("method");
new Thread(t).start();
}
}
class ThreadTest implements Runnable
{
private int tickets=100;
String str = new String ("");
public void run()
{
if(str.equals("method"))
{
while(true)
{
sale();
}
}
else
{
while(true)
{
synchronized(str)
{
if(tickets>0)
{
try
{
Thread.sleep(10);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println("Block");
System.out.println(Thread.currentThread().getName()+" is saling ticket " + tickets--);
}
}
}
}
}
public synchronized void sale()
{
if(tickets>0)
{
try
{
Thread.sleep(10);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println(Thread.currentThread().getName()+" is saling ticket " + tickets--);
}
}
}
{
public static void main(String [] args)
{
ThreadTest t=new ThreadTest();
new Thread(t).start();
try{Thread.sleep(2); //就是此处
}
catch(Exception e){
}
t.str=new String("method");
new Thread(t).start();
}
}
class ThreadTest implements Runnable
{
private int tickets=100;
String str = new String ("");
public void run()
{
if(str.equals("method"))
{
while(true)
{
sale();
}
}
else
{
while(true)
{
synchronized(str)
{
if(tickets>0)
{
try
{
Thread.sleep(10);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println("Block");
System.out.println(Thread.currentThread().getName()+" is saling ticket " + tickets--);
}
}
}
}
}
public synchronized void sale()
{
if(tickets>0)
{
try
{
Thread.sleep(10);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println(Thread.currentThread().getName()+" is saling ticket " + tickets--);
}
}
}
解决方案 »
- 关于同步
- 如何用java实现类似IE收藏夹和历史纪录的浏览器栏
- Java ImageIO读取BMP文件的问题
- 各们大侠我这个程序出了一点小问题.怎么改?
- 用什么方法将两个对象作对比,比较两个对象是否相同呢?
- 菜鸟问题,StringBuffer可以建数组吗?
- javamail再问,怎麽通过UID取message
- 如何得到一个客户端所用的代理服务器的地址?
- 有 float toFloat(int x){ return x/65536.0f;},不理解为什么除以65536.0f,请高手解释
- windows版本6.1.7601能下载最新的jdk使用吗
- 菜鸟问一个简单问题,路过的帮帮忙~~!!
- 过年了,sourceforge却上不了,特来散分。大家说,中国XX是不是有病啊,这些东西都限制了!!
相当于另一个进程刚得到运行的条件又挂起了。继续运行相前运行的进程。