朋友面试笔试阶段,限时写一个左脚踩右脚。有点紧张没写出来,笑死。。。。。记录一下,
方式1;两只脚
public class Test {
public static void main(String[] args) {
RightThread rt = new RightThread();
LiftThread lt = new LiftThread(rt);
lt.start();
}
}
class X {
static Object obj = new Object();
}
class LiftThread extends Thread {
Thread rt;
public LiftThread(Thread rt) {
this.rt = rt;
}
@Override
public void run() {
synchronized (X.obj) {
rt.start();
for (int x = 0; x < 10; x++) {
System.out.println("左脚" + x);
try {
X.obj.wait();
} catch (Exception e) {
e.printStackTrace();
}
X.obj.notify();
}
}
}
}
class RightThread extends Thread {
@Override
public void run() {
synchronized (X.obj) {
for (int x = 0; x < 10; x++) {
System.out.println(" 右脚" + x);
X.obj.notify();
try {
X.obj.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
方式二;换一种思维,可扩展性更高,四只脚
public class PrintNumber {
private int num;
private static final Object lock = new Object();
public void print(int order) {
while (true) {
synchronized (lock) {
if (num >= 120) {
break;
}
while (num % 4 == order) {
try {
System.out.println(Thread.currentThread().getName() + num);
num++;
lock.notifyAll();
lock.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
PrintNumber test = new PrintNumber();
Thread t0 = new Thread(() -> {
test.print(0);
}, "左前脚A");
Thread t1 = new Thread(() -> {
test.print(1);
}, "右后脚B");
Thread t2 = new Thread(() -> {
test.print(2);
}, "右前脚C");
Thread t3 = new Thread(() -> {
test.print(3);
}, "左后脚D");
t0.start();
t1.start();
t2.start();
t3.start();
}
}
synchronized使用的注意事项
- 若是对象锁,则每个对象都持有一把自己的独一无二的锁,且对象之间的锁互不影响 。若是类锁,所有该类的对象共用这把锁。
- 一个线程获取一把锁,没有得到锁的线程只能排队等待;
- synchronized 是可重入锁,避免很多情况下的死锁发生。
- synchronized 方法若发生异常,则JVM会自动释放锁。
- 锁对象不能为空,否则抛出NPE(NullPointerException)
- synchronized 本身是不具备继承性的:即父类的synchronized 方法,子类重写该方法,分情况讨论:没有synchonized修饰,则该子类方法不是线程同步的。
- synchronized本身修饰的范围越小越好。毕竟是同步阻塞。
synchronized的常见问题
1.同时访问synchronized的静态和非静态方法,能保证线程安全吗?
不能,两者的锁对象不一样。前者是类锁(XXX.class),后者是this
2.同时访问synchronized方法和非同步方法,能保证线程安全吗?
结论:不能,因为synchronized只会对被修饰的方法起作用。
3.两个线程同时访问两个对象的非静态同步方法能保证线程安全吗?
结论:不能,每个对象都拥有一把锁。两个对象相当于有两把锁,导致锁对象不一致。(PS:如果是类锁,则所有对象共用一把锁)
4.若synchronized方法抛出异常,会导致死锁吗?
JVM会自动释放锁,不会导致死锁问题
5.若synchronized的锁对象能为空吗?会出现什么情况?
锁对象不能为空,否则抛出NPE(NullPointerException)