线程学习(二)
一、并发
多个线程同时操作一个对象就叫做并发。

线程同步的安全性条件:队列和锁。


例子
public class DeadLock { public static void main(String[] args) { MakeUp g1 = new MakeUp(0, "白雪公主", "白雪公主"); MakeUp g2 = new MakeUp(1, "灰姑娘", "灰姑娘"); g1.start(); g2.start(); } } //镜子 class Mirror { } //口红 class LipStrick { } //化妆 class MakeUp extends Thread { static Mirror mirror = new Mirror(); static LipStrick lipStrick = new LipStrick(); private int choice; private String girlName; public MakeUp(int choice, String girlName, String name) { super(name); this.choice = choice; this.girlName = girlName; } @Override public void run() { try { makeup(); } catch (InterruptedException e) { e.printStackTrace(); } } public void makeup() throws InterruptedException { if (choice == 0) {//先拿口红 再拿镜子 synchronized (mirror) { //Thread.currentThread().getName()==this.getName() System.out.println(this.getName() + "拿到了镜子"); Thread.sleep(1000); synchronized (lipStrick) { System.out.println(this.getName() + "拿到了口红"); } } } else { synchronized (lipStrick) { System.out.println(this.getName() + "拿到了口红"); Thread.sleep(2000); synchronized (mirror) { //Thread.currentThread().getName()==this.getName() System.out.println(this.getName() + "拿到了镜子"); } } } } }
运行结果:

在这个时候就形成了死锁。

所以将上面的代码的makeup方法进行修改
public void makeup() throws InterruptedException { if (choice == 0) {//先拿口红 再拿镜子 synchronized (mirror) { //Thread.currentThread().getName()==this.getName() System.out.println(this.getName() + "拿到了镜子"); Thread.sleep(1000); } synchronized (lipStrick) { System.out.println(this.getName() + "拿到了口红"); } } else { synchronized (lipStrick) { System.out.println(this.getName() + "拿到了口红"); Thread.sleep(2000); } synchronized (mirror) { //Thread.currentThread().getName()==this.getName() System.out.println(this.getName() + "拿到了镜子"); } } }
再次运行后的结果


public class TestLock { public static void main(String[] args) { BuyTicket buyTicket = new BuyTicket(); new Thread(buyTicket).start(); new Thread(buyTicket).start(); new Thread(buyTicket).start(); } } class BuyTicket implements Runnable { private int ticketNum = 10; private final ReentrantLock lock = new ReentrantLock(); @Override public void run() { while (true) { //开启锁 lock.lock(); try { if (ticketNum > 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(ticketNum--); } else { break; } } finally { //结束锁 lock.unlock(); } } } }



浙公网安备 33010602011771号