新手上路
总容易弄出些低级错误。
synchronized写了个3线程抢票发现一直只执行一个
class ticket implements Runnable {
private int num = 100;
@Override
public synchronized void run() {
while (num >= 0) {
if (num == 0) {
break;
}
System.out.println("剩余:" + num-- + Thread.currentThread().getName());
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
新手不懂,直接run加上synchronied,
synchronied 线程进入 会执行到方法完毕,所以会一直在while 里面循环,然后推出。所以只有一个线程抢完所有的票然后其他线程才会进来。
修改方法 写个synchronized方法 把num – 扔进去
class ticket implements Runnable {
private int num = 100;
@Override
public void run() {
while (num >= 0) {
if (num == 0) {
break;
}
sell();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void sell(){
System.out.println("剩余:" + num-- + Thread.currentThread().getName());
}
}
嫌麻烦的 直接
synchronized (this) {
System.out.println("剩余:" + num-- + Thread.currentThread().getName());
}
synchronized 的基本使用
1.同步方法(非静态的)的锁可以是this也可以是其他对象,要求是同一对象
2.同步方法(静态的)的锁为当前类的本身。
public class A {
Object object = new Object();
public void m(){
synchronized (object){
}
synchronized (this){
}
}
public static void n(){
synchronized (A.class){
}
}
}