public class ThreadDemo1 { 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//extends Thread
{
int tickets = 100;
String str = new String("aa");
public void run()
{
while (true) {
synchronized(str)//我使用了线程同步,最后运行的时候怎么还是会出现负数的情况呢?
{
if(tickets>0)
try{
Thread.sleep(10);
}catch(Exception ex){
System.out.println(ex.getMessage());
}
System.out.println("run():"+Thread.currentThread().getName()+"is sailing ticket"+tickets--);
if(tickets<-10)
System.exit(0);
}
}
}
}
反而我把synchronize语句去了之后到是可以实现同步了;这是为什么呢?
初学JAVA;请教各位大哥;
synchronize是实现同步的
没有synchronize就不同步了
我加了synchronize反而不同步;
搞的我好郁闷;
但是我加了该语句之后为了测试synchronize的功能;
可加了和没加一样;是什么问题啊?
卖票的时候,就是2张火车票不会被卖2次.当卖到只剩0张的时候,其他的线程不会误认为还有票.
你把循环的条件判断改下,不就是可以不出现负数了.
if(tickets <0)
System.exit(0);
(如果你把synchronized(str)去掉,就会出现-1,-2,-3的情况!)
帮你改了你看下吧。public class ThreadDemo1 { 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();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
}}class TestThread implements Runnable
{
int tickets = 100; public void run() {
while (true) {
synchronized (ThreadDemo1.class) {// 去掉这个就会有负数了
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
System.out.println("run():"
+ Thread.currentThread().getName()
+ "is sailing ticket" + tickets--);
} else {
break;
}
}
}
}
}
必须要break?