Multi-Programming-15 线程顺序执行

来源:互联网 发布:淘宝和易趣的相同点 编辑:程序博客网 时间:2024/06/05 14:26

1. 问题

Q:假设有三个线程,假设为t1, t2, t3, 如何保证线程的顺序执行t1->t2->t3?
A:首先,java语言多线程机制并没有执行顺序的属性;其次,设置线程的优先级并不能确保线程的准确执行顺序。所以,这里需要采用其他方式保证执行了。
本文提供了三种解决方式:
1). ReentrantLock: 重入锁方案。
2). Condition: 类似于wait(), notify()
3). Semaphore: 利用互斥信号量解决。

2. 解决思路

2.1 ReentrantLock机制

package com.fqyuan._10sequenceExecute;import java.util.concurrent.locks.ReentrantLock;public class SequenceStop {    private static ReentrantLock lock = new ReentrantLock();    private /* volatile */ static int state = 0;    public static void main(String[] args) {        new Thread1().start();        new Thread2().start();        new Thread3().start();    }    static class Thread1 extends Thread {        /*         * 主要有以下问题: 1)使用了int变量计数保证了线程的执行顺序;         * 2)每次for循环之后的变量更新条件是在if语句中变化的,如果state条件没有满足则线程释放所获取的锁对象。         * 3)因为对于state的访问是在锁获取之间进行的,可以保证是同步访问的,故而可以不使用volatile关键字。         */        @Override        public void run() {            for (int i = 0; i < 10;) {                lock.lock();                if (state % 3 == 0) {                    try {                        Thread.sleep(500);                    } catch (InterruptedException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                    System.out.print("A");                    state++;                    i++;                }                lock.unlock();            }        }    }    static class Thread2 extends Thread {        @Override        public void run() {            for (int i = 0; i < 10;) {                lock.lock();                if (state % 3 == 1) {                    try {                        Thread.sleep(500);                    } catch (InterruptedException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                    System.out.print("B");                    state++;                    i++;                }                lock.unlock();            }        }    }    static class Thread3 extends Thread {        @Override        public void run() {            for (int i = 0; i < 10;) {                lock.lock();                if (state % 3 == 2) {                    try {                        Thread.sleep(500);                    } catch (InterruptedException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                    System.out.print("C");                    state++;                    i++;                }                lock.unlock();            }        }    }}

2.2 Condiotn

package com.fqyuan._10sequenceExecute;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;public class SequenceStop1 {    private static ReentrantLock lock = new ReentrantLock();    private static Condition A = lock.newCondition();    private static Condition B = lock.newCondition();    private static Condition C = lock.newCondition();    private static int count = 0;    public static void main(String[] args) {        new Thread1().start();        new Thread2().start();        // 因为主线程和用户线程是并发执行的,如果没有thread.join()语句,则打印的结果将为0        Thread thread3 = new Thread3();        thread3.start();        try {            thread3.join();        } catch (InterruptedException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        System.out.println(count);    }    static class Thread1 extends Thread {        /*         * 和纯粹使用ReentrantLock类似,都是用了一个int类型量决定线程的执行顺序。         * 不过使用了Conditon之后更加灵活。注意以下问题: 1) 使用了while语句判别wait条件是为了防止spurious         * wakeup; 2) 在调用了await之后,线程将放弃当前的lock; 3)signal将会唤醒等待在该condition的线程。         */        @Override        public void run() {            try {                lock.lock();                for (int i = 0; i < 10; i++) {                    while (count % 3 != 0)                        A.await(); // Release the lock it owns now!                    Thread.sleep(500);                    System.out.print("A");                    count++;                    B.signal();                }            } catch (InterruptedException e) {                e.printStackTrace();            } finally {                lock.unlock();            }        }    }    static class Thread2 extends Thread {        @Override        public void run() {            lock.lock();            try {                for (int i = 0; i < 10; i++) {                    while (count % 3 != 1)                        B.await();                    Thread.sleep(500);                    System.out.print("B");                    count++;                    C.signal();                }            } catch (InterruptedException e) {                e.printStackTrace();            } finally {                lock.unlock();            }        }    }    static class Thread3 extends Thread {        @Override        public void run() {            lock.lock();            try {                for (int i = 0; i < 10; i++) {                    while (count % 3 != 2)                        C.await();                    Thread.sleep(500);                    System.out.print("C");                    count++;                    A.signal();                }            } catch (InterruptedException e) {                e.printStackTrace();            } finally {                lock.unlock();            }        }    }}

2.3 使用互斥信号量

相对于使用ReentrantLock而言整体上较为简单,无须设置保证顺序的整形变量。但是在运行时需注意将非首先执行的线程信号量的availablePermits 置为0.
信号量的acquire() & release()是环形进行的,这样保证了执行的顺序!

package com.fqyuan._10sequenceExecute;import java.util.concurrent.Semaphore;public class SequenceStop2 {    private static Semaphore A = new Semaphore(1);    private static Semaphore B = new Semaphore(1);    private static Semaphore C = new Semaphore(1);    public static void main(String[] args) throws InterruptedException {        B.acquire();        C.acquire();        new ThreadA().start();        new ThreadB().start();        new ThreadC().start();    }    static class ThreadA extends Thread {        @Override        public void run() {            try {                for (int i = 0; i < 10; i++) {                    A.acquire();                    System.out.print("A");                    Thread.sleep(500);                    B.release();                }            } catch (InterruptedException e) {            }        }    }    static class ThreadB extends Thread {        @Override        public void run() {            try {                for (int i = 0; i < 10; i++) {                    B.acquire();                    System.out.print("B");                    Thread.sleep(500);                    C.release();                }            } catch (InterruptedException e) {            }        }    }    static class ThreadC extends Thread {        @Override        public void run() {            try {                for (int i = 0; i < 10; i++) {                    C.acquire();                    System.out.print("C");                    Thread.sleep(500);                    A.release();                }            } catch (InterruptedException e) {            }        }    }}
//Running result:ABCABCABCABCABCABCABCABCABCABC

3. 说明

本文内容参考自此处,可自行查看。

原创粉丝点击