我在听 **老师的视频课程时候 讲的线程 两种方法的同步 同步代码块里是一个 String 类型的 另一个用的是 同步方法
老师讲解的是 这样不能同步 模拟售票 售出了 第0张票 然后 又将 String类型的对象 改为this 同步成功
可我在我自己的电脑上 重新编写的时候 用String对象 时候 同步没问题 没有卖 第0张 票 换成了 this 后 显示结果 却有点怪异 先是 一个线程卖了 几张票以后 转到第二个 线程 执行 然后一直是这个线程卖完了所有的票 怎么回事???
程序代码 如下:
package thread;public class Class3 {
public static void main(String[] args) throws Exception {
ClassTest t=new ClassTest();
new Thread(t).start();
Thread.sleep(1);
t.str=new String("second");
new Thread(t).start();
}}class ClassTest implements Runnable
{
int tickets=300;
String str=new String(" ");
public void run()
{
if(str.equals("second"))
{
while(true)
{
sell();
if(tickets==0)
System.exit(0);
}
}
else
{
while(true)
{
synchronized(this)
{
if(tickets>0)
{
System.out.println("main function"+Thread.currentThread().getName()+" sell tickets "+tickets--);
if(tickets==0)
System.exit(0);
}
}
}
}
}
public synchronized void sell()
{
while(true)
{
if(tickets>0)
{
System.out.println("sell function "+Thread.currentThread().getName()+" sell tickets "+tickets--);
}
if(tickets==0)
System.exit(0);
}
}
}
老师讲解的是 这样不能同步 模拟售票 售出了 第0张票 然后 又将 String类型的对象 改为this 同步成功
可我在我自己的电脑上 重新编写的时候 用String对象 时候 同步没问题 没有卖 第0张 票 换成了 this 后 显示结果 却有点怪异 先是 一个线程卖了 几张票以后 转到第二个 线程 执行 然后一直是这个线程卖完了所有的票 怎么回事???
程序代码 如下:
package thread;public class Class3 {
public static void main(String[] args) throws Exception {
ClassTest t=new ClassTest();
new Thread(t).start();
Thread.sleep(1);
t.str=new String("second");
new Thread(t).start();
}}class ClassTest implements Runnable
{
int tickets=300;
String str=new String(" ");
public void run()
{
if(str.equals("second"))
{
while(true)
{
sell();
if(tickets==0)
System.exit(0);
}
}
else
{
while(true)
{
synchronized(this)
{
if(tickets>0)
{
System.out.println("main function"+Thread.currentThread().getName()+" sell tickets "+tickets--);
if(tickets==0)
System.exit(0);
}
}
}
}
}
public synchronized void sell()
{
while(true)
{
if(tickets>0)
{
System.out.println("sell function "+Thread.currentThread().getName()+" sell tickets "+tickets--);
}
if(tickets==0)
System.exit(0);
}
}
}
t.str=new String("second");
然后,在run方法里,你有
if(str.equals("second"))
那么,在你的第一个线程启动之后,执行
new Thread(t).start();
Thread.sleep(1);
之后,t.str就已经变成了“second”,也就是说,在你的run方法里
if(str.equals("second"))语句判断条件总是成立的!那么else分支就根本就不会执行了!
出现你说的结果就不足为奇了。
你试试删掉
t.str=new String("second");
这一句看看。
synchronized(this) {
if(tickets>0)
System.out.println("main function"+Thread.currentThread().getName()+" sell tickets "+tickets--);
if(tickets==0)
System.exit(0);
}
了么,还难返回去在判断么
synchronized 方法就是synchronized (this)