知识总结
- 同步规则:
(1)只有在调用包含同步代码块的方法,或者同步方法时,才需要对象的锁标记
(2)如调用不包含同步代码块的方法,或普通方法时,则不需要锁标记,可直接调用 - JDK已知线程安全类:
StringBuffer
Vector
Hashtable
均为synchonized修饰的同步方法 - 死锁:
(1)当第一个线程拥有A对象锁标记,并等待B对象锁标记,同时第二个线程拥有B对象锁标记,并等待A对象锁标记时,产生死锁。
(2)一个线程可以同时拥有多个对象的锁标记,当线程阻塞时,不会释放已经拥有的锁标记,由此可能造成死锁。
每日练习
答:AC
答:
public class TestMyThread {
public static void main(String[] args) {
Runnable t1 = new MyThread1();
Thread t2 = new MyThread2();
Thread t3 = new Thread(t1);
t3.start();
t2.start();
}
}
class MyThread1 implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("hello");
}
}
}
class MyThread2 extends Thread {
public void run() {
for (int i = 0; i < 100; i++) {
try {
this.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("world");
}
}
}