代码如下:public class five2
{
public static void main(String [] args)
{
synchronizedtest t =new synchronizedtest();
new Thread(t).start();
try{Thread.sleep(1);}catch(Exception e){}
t.str=new String("method");
new Thread(t).start();
}
}class synchronizedtest implements Runnable
{
private int tickets=100;
String str=new String ("");
public void run()
{
if(str.equals("method"))
{
while(true)
{
sale();
}
}
else
{
while(true)
{
synchronized(this)
{
if(tickets > 0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread() .getName() +" ticket is saling" +tickets--);
}
}
}
}
}
public synchronized void sale()
{ if(tickets > 0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.print("in the test:");
System.out.println(Thread.currentThread().getName()+ " ticket is saling" + tickets--);
}
}
}
在张孝祥培训教程上看到的
希望能实现sale()函数与run()中的代码段交替输出
但是结果总是代码段单独输出 不知道出错在哪里 希望各位帮忙看下 十分感激~~
祝大家新年快乐~
{
public static void main(String [] args)
{
synchronizedtest t =new synchronizedtest();
new Thread(t).start();
try{Thread.sleep(1);}catch(Exception e){}
t.str=new String("method");
new Thread(t).start();
}
}class synchronizedtest implements Runnable
{
private int tickets=100;
String str=new String ("");
public void run()
{
if(str.equals("method"))
{
while(true)
{
sale();
}
}
else
{
while(true)
{
synchronized(this)
{
if(tickets > 0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread() .getName() +" ticket is saling" +tickets--);
}
}
}
}
}
public synchronized void sale()
{ if(tickets > 0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.print("in the test:");
System.out.println(Thread.currentThread().getName()+ " ticket is saling" + tickets--);
}
}
}
在张孝祥培训教程上看到的
希望能实现sale()函数与run()中的代码段交替输出
但是结果总是代码段单独输出 不知道出错在哪里 希望各位帮忙看下 十分感激~~
祝大家新年快乐~
Thread-0 ticket is saling100
Thread-0 ticket is saling99
Thread-0 ticket is saling98
Thread-0 ticket is saling100
in the test:Thread-1 ticket is saling99
…………
…………
…………
不知道这样的话是咋错了……