public class Demo{
public static int rocket = 20;
public static void main(String[] args){
MyThread mt1 = new MyThread();
Thread t1 = new Thread(mt1);
MyThread2 t2 = new MyThread2();
t1.start();
t2.start();
}
}
class MyThread implements Runnable{
public void run(){
synchronized("11"){
while(Demo.rocket>0){
if(Demo.rocket==1){
try{
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
}
Demo.rocket--;
System.out.println("1111卖票,剩余:"+Demo.rocket+"张票");
}
}
}
}
class MyThread2 extends Thread{
public void run(){
synchronized("11111"){
while(Demo.rocket>0){
Demo.rocket--;
System.out.println("22222222卖票,剩余 :"+Demo.rocket+"张票........");
}
}
}
}
结果:
1111卖票,剩余:19张票
22222222卖票,剩余 :18张票.....
1111卖票,剩余:17张票
22222222卖票,剩余 :16张票.....
1111卖票,剩余:15张票
1111卖票,剩余:13张票
22222222卖票,剩余 :14张票.....
1111卖票,剩余:12张票
22222222卖票,剩余 :11张票.....
22222222卖票,剩余 :9张票......
22222222卖票,剩余 :8张票......
1111卖票,剩余:10张票
1111卖票,剩余:6张票
1111卖票,剩余:5张票
22222222卖票,剩余 :7张票......
22222222卖票,剩余 :3张票......
1111卖票,剩余:4张票
1111卖票,剩余:1张票
22222222卖票,剩余 :2张票......
22222222卖票,剩余 :0张票......
1111卖票,剩余:-1张票
为啥结果还有-1啊?怎样解决?
------解决方案--------------------
有-1是线程同步现象导致的,判断while条件的时候肯定是满足的,进去执行的时候,另一个线程将Demo.rocket执行的结果为0.所以……
------解决方案--------------------
要锁住demo这个对象
package com.xiehou.th;
public class Demo {
public static int rocket = 20;
public static void main(String[] args) {
Demo demo=new Demo();
MyThread mt1 = new MyThread(demo);
Thread t1 = new Thread(mt1);
MyThread2 t2 = new MyThread2(demo);
t1.start();
t2.start();
}
}
class MyThread implements Runnable {
public Demo demo;
public MyThread(Demo demo){
this.demo=demo;
}
public void run() {
synchronized (demo) {
while (Demo.rocket > 0) {
if (Demo.rocket == 1) {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
Demo.rocket--;
System.out.println("[1111]卖第:" + Demo.rocket + "张票");
}
}
}
}
class MyThread2 extends Thread {
public Demo demo;
public MyThread2(Demo demo){
this.demo=demo;
}
public void run() {
synchronized (demo) {
while (Demo.rocket > 0) {
Demo.rocket--;
System.out.println("[2222]第 :" + Demo.rocket + "张票");
}
}
}
}
------解决方案--------------------
你两个锁不是同一个锁,不起作用的,要锁同一个对象才行的。