多线程信息共享-加锁
- 关键步骤加锁限制
– 互斥:某一个线程运行一个代码段(关键区),其他线程不能同时运行这个代码段
– 同步:多个线程的运行,必须按照某一种规定的先后顺序来运行
– 互斥是同步的一种特例 - 互斥的关键字是synchronized
– synchronized代码块/函数,只能一个线程进入
– synchronized加大性能负担,但是使用简便
public class ThreadDemo3 {
public static void main(String[] args){
TestThread3 t = new TestThread3();
new Thread(t,"Thread-0").start();
new Thread(t,"Thread-1").start();
new Thread(t,"Thread-2").start();
new Thread(t,"Thread-3").start();
}
}
class TestThread3 implements Runnable{
private volatile int tickets=100;
private static Object o=new Object();
public void run() {
while (true){
synchronized (o){
sale();
}
try{
Thread.sleep(100);
}catch (Exception ex){
ex.printStackTrace();
}
if (tickets<=0) {
break;
}
}
}
private synchronized void sale() {
if (tickets>0) {
System.out.println(Thread.currentThread().getName() + " is saling ticket " + (tickets--));
}
}
}