//测试类
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 后面的不打印了?????

解决方案 »

  1.   

    此问题已经解决!
    package com.wb;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();
    }
    }class ThreadTest1 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(50);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    System.out.println("同步代码块");
    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("同步函数");
    System.out.println(Thread.currentThread().getName()
    + "is saling ticket " + tickets--);
    }
    }
    }
      

  2.   

    你蒙我呢?str.equals("method")不为真,执行else部分:没有循环
    你开了俩线程,当然只打两次