8-1
(1)同步代码块:
public class Ticket implements Runnable {
//共100票
int ticket = 100;
//定义锁对象
Object lock = new Object();
@Override
public void run() {
//模拟卖票
while(true){
//同步代码块
synchronized (lock){
if (ticket > 0) {
//模拟电影选坐的操作
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在卖票:" + ticket--);
}
}
}
}
}
8-2
(2)同步方法:
public class Ticket implements Runnable {
//共100票
int ticket = 100;
//定义锁对象
Object lock = new Object();
@Override
public void run() {
//模拟卖票
while(true){
//同步方法
method();
}
}
//同步方法,锁对象this
public synchronized void method(){
if (ticket > 0) {
//模拟选坐的操作
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在卖票:" + ticket--);
}
}
}
8-3
(3)同步锁
public class Ticket implements Runnable {
//共100票
int ticket = 100;
//创建Lock锁对象
Lock ck = new ReentrantLock();
@Override
public void run() {
//模拟卖票
while(true){
//synchronized (lock){
ck.lock();
if (ticket > 0) {
//模拟选坐的操作
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在卖票:" + ticket--);
}
ck.unlock();
//}
}
}
}
9-1
1. public class Singleton {
2. private static Singleton instance;
3. private Singleton (){}
4.
5. public static Singleton getInstance() {
6. if (instance == null) {
7. instance = new Singleton();
8. }
9. return instance;
10. }
11. }
9-2
1. public class Singleton {
2. private static Singleton instance;
3. private Singleton (){}
4. public static synchronized Singleton getInstance() {
5. if (instance == null) {
6. instance = new Singleton();
7. }
8. return instance;
9. }
10. }
9-3
1. public class Singleton {
2. private static Singleton instance = new Singleton();
3. private Singleton (){}
4. public static Singleton getInstance() {
5. return instance;
6. }
7. }
9-4
1. public class Singleton {
2. private Singleton instance = null;
3. static {
4. instance = new Singleton();
5. }
6. private Singleton (){}
7. public static Singleton getInstance() {
8. return this.instance;
9. }
10. }
9-5
1. public class Singleton {
2. private static class SingletonHolder {
3. private static final Singleton INSTANCE = new Singleton();
4. }
5. private Singleton (){}
6. public static final Singleton getInstance() {
7. return SingletonHolder.INSTANCE;
8. }
9. }
9-6
1. public enum Singleton {
2. INSTANCE;
3. public void whateverMethod() {
4. }
5. }
9-7
1. public class Singleton {
2. private volatile static Singleton singleton;
3. private Singleton (){}
4. public static Singleton getSingleton() {
5. if (singleton == null) {
6. synchronized (Singleton.class) {
7. if (singleton == null) {
8. singleton = new Singleton();
9. }
10. }
11. }
12. return singleton;
13. }
14. }