1.同步代码块
格式:
synchronized(同步对象){
需要同步的代码块;
}
示例:
class MyThreadDemo implements Runnable {
private int ticket = 5;// 五张票
public void run() {
for (int i = 0; i < 10; i++) {
// 解决资源共享就需要同步
synchronized (this) {
if (ticket > 0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("车窗:" + Thread.currentThread().getName()
+ " 出车票:" + ticket--);
}
}
}
}
}
public class ThreadDemo05 {
public static void main(String[] args) {
MyThreadDemo m = new MyThreadDemo();
// 三个购票窗口
Thread t1 = new Thread(m);
Thread t2 = new Thread(m);
Thread t3 = new Thread(m);
t1.start();
t2.start();
t3.start();
}
}
运行结果:
2.同步方法
格式:
synchronized void 方法名称(){}
示例:
class MyThreadDemo implements Runnable {
private String name;
private int ticket = 5;// 五张票
public void run() {
for (int i = 0; i < 10; i++) {
tell();
}
}
// 同步方法
public synchronized void tell() {
if (ticket > 0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("车窗:" + Thread.currentThread().getName()
+ " 出车票:" + ticket--);
}
}
}
public class ThreadDemo05 {
public static void main(String[] args) {
MyThreadDemo m = new MyThreadDemo();
// 三个购票窗口
Thread t1 = new Thread(m);
Thread t2 = new Thread(m);
Thread t3 = new Thread(m);
t1.start();
t2.start();
t3.start();
}
}
结果:
3.死锁:
是指两个或两个以上的进程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程。