【Java】线程死锁

2021/7/24 12:16:38

本文主要是介绍【Java】线程死锁,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

以下可能造成死锁的代码是?
A.

public class LeftRightLock {
    private final Object left = new Object();
    private final Object right = new Object();

    public void functionA() {
        synchronized (left) {
            synchronized (right) {
                doSomething();
            }
        }
    }
    public void functionB() {
        synchronized (right) {
            synchronized(left) {
                doSomething();
            }
        }
    }
}

B.

    public void transferMony(Account fromAccount, Account toAccount, int amount) {
        synchronized (fromAccount) {
            synchronized(toAccount) {
                fromAccount.debit(amount);
                toAccount.credit(amount);
            }
        }
    }

C.

public class Taxi {
    private Point location;
    private Point destinztion;
    private final Dispatcher dispatcher;
    public Taxi(Dispatcher dispatcher) {
        this.dispatcher = dispatcher;
    }
    public synchronized Point getLocation() {
        return location;
    }
    public synchronized void setLocation(Point location) {
        this.location = location;
        if (this.location.equals(destinztion)) {
            dispatcher.notifyAvailable(this);
        }
    }
}
public class Dispatcher {
    private final Set<Taxi> taxis = new HashSet<>();
    private final Set<Taxi> availableTaxis = new HashSet<>();

    public synchronized void notifyAvailable(Taxi taxi) {
        availableTaxis.add(taxi);
    }
    public synchronized Image getImage() {
        final Image image = new Image();
        for (final Taxi taxi : taxis) {
            image.drawMarket(taxi.getLocation());
        }
        return image;
    }
}

D.

    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    public void renderPage() throws InterruptedException, ExecutionException {
        Future<String> page = executor.submit(new RenderPageTask());
        frame.set(page.get());
    }
public class RenderPageTask implements Callable<String> {
    @Override
    public String call() throws Exception {
        final Future<String> header = executor.submit(new LoadFileTask("head.html"));
        final Future<String> foot = executor.submit(new LoadFileTask("foot.html"));
        return header.get() + "page" + foot.get();
    }
}

A:锁顺序死锁。

B:动态锁顺序死锁。

C:协作对象之间发生死锁。

D:线程饥饿死锁。



这篇关于【Java】线程死锁的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程