synchronized 线程同步
多线程售票实现
public class MyThread extends Thread {
public static int tickets = 100;
@Override
public void run() {
// TODO Auto-generated method stub
int count = 0;
while (true) {
if (tickets > 0) {
System.out
.printf("%s第%d次卖票,正在卖出第%d张票,剩余%d张票\n", Thread
.currentThread().getName(), ++count, tickets,
--tickets);
try {
Thread.sleep(3); // 售票后等待3毫秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(1);
}
} else {
break;
}
}
}
}
public class test{
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.setName("售票处1");
t2.setName("售票处2");
t3.setName("售票处3");
t1.start();
t2.start();
t3.start();
}
}
运行结果:未添加线程同步,出现数据混乱情况
添加线程锁后,解决数据混乱问题
public class MyThread extends Thread {
public static int tickets = 100;
@Override
public void run() {
// TODO Auto-generated method stub
int count = 0;
while (true) {
//!!!!!!!!!!!!!!
synchronized (MyThread.class) {
//!!!!!!!!!!!!!!
if (tickets > 0) {
System.out.printf("%s第%d次卖票,正在卖出第%d张票,剩余%d张票\n", Thread
.currentThread().getName(), ++count, tickets,
--tickets);
try {
Thread.sleep(3); // 售票后等待3毫秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(1);
}
} else {
break;
}
}
}
}
}
运行结果:添加线程同步后,数据显示正常
也可以如下使用 synchronized 关键字实现线程同步,效果与上述方法相同
public class MyThread extends Thread {
public static int tickets = 100;
@Override
public synchronized void run() {
// TODO Auto-generated method stub
int count = 0;
while (true) {
if (tickets > 0) {
System.out.printf("%s第%d次卖票,正在卖出第%d张票,剩余%d张票\n", Thread
.currentThread().getName(), ++count, tickets,
--tickets);
try {
Thread.sleep(3); // 售票后等待3毫秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(1);
}
} else {
break;
}
}
}
}