//测试类
public class ThreadDemo6
{
public static void main(String[] args)
{
ThreadTest1 t=new ThreadTest1();
new Thread(t).start();
t.str=new String("methord");//不是method
new Thread(t).start();
}
}
//
public class ThreadTest1 implements Runnable
{
private int tickets=100;
String str=new String("");
public void run()
{
if(str.equals("method"))
{
while(true)
{
sale();
}
}
else
{
synchronized(str)
{
if(tickets>0)
{
try
{
Thread.sleep(50);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
System.out.println("fs");
System.out.println(Thread.currentThread().getName()+
"is saling ticket "+tickets--);
}
}
}
}
public synchronized void sale()
{
if(tickets>0)
{
try
{
Thread.sleep(1155);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
System.out.println("fsfasfs");
System.out.println(Thread.currentThread().getName()+
"is saling ticket "+tickets--);
}
}
}
=======================================================================
----------java ----------
fs
Thread-0is saling ticket 100
fs
Thread-1is saling ticket 99输出完成 (耗时 0 秒) - 正常终止
为什么不把只打印100 99 后面的不打印了?????
public class ThreadDemo6
{
public static void main(String[] args)
{
ThreadTest1 t=new ThreadTest1();
new Thread(t).start();
t.str=new String("methord");//不是method
new Thread(t).start();
}
}
//
public class ThreadTest1 implements Runnable
{
private int tickets=100;
String str=new String("");
public void run()
{
if(str.equals("method"))
{
while(true)
{
sale();
}
}
else
{
synchronized(str)
{
if(tickets>0)
{
try
{
Thread.sleep(50);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
System.out.println("fs");
System.out.println(Thread.currentThread().getName()+
"is saling ticket "+tickets--);
}
}
}
}
public synchronized void sale()
{
if(tickets>0)
{
try
{
Thread.sleep(1155);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
System.out.println("fsfasfs");
System.out.println(Thread.currentThread().getName()+
"is saling ticket "+tickets--);
}
}
}
=======================================================================
----------java ----------
fs
Thread-0is saling ticket 100
fs
Thread-1is saling ticket 99输出完成 (耗时 0 秒) - 正常终止
为什么不把只打印100 99 后面的不打印了?????
解决方案 »
- 新人求教,简单方法同步问题,请各位大神指点.
- java实现ping命令
- 这段小程序点击菜单项怎么没有反应????
- 一道面试题帮忙组织下--怎么样概述java中常见的集合类和接口
- 执行Java的批处理文件,如何让它显示自定义的名称,如TOMCAT启动的界面显示TOMCAT
- JTextField的问题
- 大家帮帮忙看一下这个该怎么写?有关对象变量
- statment执行存储过程如果取参数的值?
- java的学习方法
- java 如何写日志文件?
- 关于随机取值的问题???高手指教!!
- 请教连sql server2000的出现 jdbc connection reset by peer:socket write error
在这里代码这么乱不知情的还真有点难看程序里str都是不等于"method"所以都执行else部分;
而只在if部分有while循环
故
一个线程只执行一次打印
两个线程就两次啊另外,若str等于"method"会出现死循环吧