关于java中的synchronized关键字的问题

来源:百度知道 编辑:UC知道 时间:2024/07/02 05:18:47
先看看下面的程序(简单模仿卖票过程)
/*在下面的程序里,创建了四个线程,每一个线程调用的是同一个TestThread对象中的run()方法,
访问的是同一个对象中的变量(tickets)的实例
*/
public class TicketsThread
{
public static void main(String[] args)
{
TestThread tt = new TestThread();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
}
}

class TestThread implements Runnable
{
private int tickets=100;
String str= new String("");
public void run()
{
/*
///*这里把for语句称为代码1
for(;tickets>0;)
{
synchronized(str)
{
try
{ Thread.sleep(5); }
catch(Exception e)
{ System.out.println(e.getMessage()); }
System.out.println(Thread.currentThread().getName() + " is selling ticket "+tickets--);
}
}
*/
//*把while语句称为代码2
while(true)
{
synchronize

一些重要的判断要放在同步块里面吧。。
你改成这样子就没事了
synchronized(str)
{
for(;tickets>0;)
{
try
{ Thread.sleep(5); }
catch(Exception e)
{ System.out.println(e.getMessage()); }
System.out.println(Thread.currentThread().getName() + " is selling ticket "+tickets--);
}

}

synchronized(str){
for(;tickets>0;)
{
try
{ Thread.sleep(5); }
catch(Exception e)
{ System.out.println(e.getMessage()); }
System.out.println(Thread.currentThread().getName() + " is selling ticket "+tickets--);
}
}
这样子改一下就行了 其实线程同步了的 只是因为它们是先进循环再同步的

所以进了循环的线程至少会输出一次

也可以在输出前加一个判断条件如下:

for(;tickets>0;)
{
synchronized(str)
{
try
{ Thread.sleep(5); }
catch(Exception e)
{ System.out.println(e.getMessage()); }
if(0<tickets)
System.out.println(Thread.currentThread().getName() + " is selling ticket "+tickets--);<