Execution order of multiple threads

前端 未结 4 1781
失恋的感觉
失恋的感觉 2020-12-03 16:43

Let\'s say we have this scenario:

class Stack{

public void main{

ChildThread1 t1 = new ChildThread1;
ChildThread1 t2 = new ChildThread1;
ChildThread1 t3 =          


        
4条回答
  •  庸人自扰
    2020-12-03 17:00

    Easy way to maintain ordering in Thread Execution is to use Semaphore

    public class Semaphore {
    
    int value;
    
    public Semaphore(int intialValue) {
        this.value = intialValue;
    }
    
    public synchronized void p() {
        while (value <= 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
            }
    
        }
        value = value - 1;
    }
    
    public synchronized void v() {
        value = value + 1;
        this.notify();
    }
    

    }

    public class ThreadSync {
    
    static Semaphore semaphore = new Semaphore(0);
    
    public static void main(String[] args) {
        // t1 should be executed before t2
        Thread t1 = new Thread(new Runnable() {
    
            @Override
            public void run() {
                semaphore.p();
                System.out.println("executing " + Thread.currentThread().getName());
            }
        });
        Thread t2 = new Thread(new Runnable() {
    
            @Override
            public void run() {
                System.out.println("executing " + Thread.currentThread().getName());
                semaphore.v();
            }
        });
    
        t1.setName("Thread 1");
        t2.setName("Thread 2");
        t2.start();
        t1.start();
    
    }
    

    }

提交回复
热议问题