Java多线程模式之Single Threaded Execution

 Single Threaded Execution:  该模式能保证最多有一个线程执行指定的方法

 何时使用: 1. 多线程环境

                  2. 多线程存在共享的资源

                  3. 共享的资源是可变的

  以上3个条件缺一不可

 

 

 

 Single Threaded Execution模式如果同时满足下列几个条件时,就会产生死锁:

  1. 每个线程 同时需要1个以上共享资源

  2. 每个线程的一个操作在锁定一个资源的时候,还没解除前就去锁定另一个资源

  3。每个线程对操作对资源需要的顺序不一样

 

Main:

public class Main {
    public static void main(String[] args) {
        System.out.println("Testing EaterThread, hit CTRL+C to exit.");
        Tool spoon = new Tool("Spoon");
        Tool fork = new Tool("Fork");
        new EaterThread("Alice", fork, spoon ).start();
        new EaterThread("Bobby", spoon, fork).start();
    }
}

 

Tool:

public class Tool {
    private final String name;
    public Tool(String name) {
        this.name = name;
    }
    public String toString() {
        return "[ " + name + " ]";
    }
}

 

EaterThread:

 

public class EaterThread extends Thread {
    private String name;
    private final Tool lefthand;
    private final Tool righthand;
    public EaterThread(String name, Tool lefthand, Tool righthand) {
        this.name = name;
        this.lefthand = lefthand;
        this.righthand = righthand;
    }
    public void run() {
        while (true) {
            eat();
        }
    }
    public void eat() {
        synchronized (lefthand) {
            System.out.println(name + " takes up " + lefthand + " (left).");
            synchronized (righthand) {
                System.out.println(name + " takes up " + righthand + " (right).");
                System.out.println(name + " is eating now, yam yam!");
                System.out.println(name + " puts down " + righthand + " (right).");
            }
            System.out.println(name + " puts down " + lefthand + " (left).");
        }
    }
}

 

 

 

 

 

 

 

 

你可能感兴趣的:(多线程,多线程,Java,UP,thread,C)