您的位置:首页 > 编程语言 > Java开发

Java线程同步 1

2008-09-30 21:42 387 查看
PART.1  ReentrantLock<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

 

1. 通过ReentrantLock的lock和unlock方法获得和释放锁。

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest

{

    private static ReentrantLock locker = new ReentrantLock();

    

    public static void main(String[] args) throws Exception

    {

        Thread th = new Thread(new TestRunnable());

        

        System.out.println("main: lock.");

        locker.lock();

        

        System.out.println("main: starting Test.");

        th.start();

        

        System.out.println("main: sleep for 3 seconds.");

        Thread.sleep(3000);

        

        System.out.println("main: unlock.");

        locker.unlock();

    }

    

    private static class TestRunnable implements Runnable

    {

        @Override

        public void run()

        {

            System.out.println("test: start and lock.");

            locker.lock();

            System.out.println("test: between lock and unlock.");

            locker.unlock();

            System.out.println("test: end.");

        }

    }

}

2.2个线程分别向counter加10,每次加1。

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest2

{

    private static ReentrantLock locker = new ReentrantLock();

    private static int counter = 0;

    

    public static void main(String[] args) throws Exception

    {

        Thread th1 = new Thread(new TestRunnable());

        Thread th2 = new Thread(new TestRunnable());

        

        th1.start();

        th2.start();

        

        th1.join();

        th2.join();

        

        System.out.println(counter);

    }

    

    private static class TestRunnable implements Runnable

    {

        @Override

        public void run()

        {

            for (int i = 0; i < 10; i++)

            {

                locker.lock();

                try

                {

                    int temp = counter + 1;

                    Thread.sleep(100);

                    counter = temp;

                }

                catch (InterruptedException e)

                {

                    return;

                }

                finally

                {

                    locker.unlock();

                }

            }

        }

    }

}

PART.2 Condition

 

1.       通过ReentrantLock创建Condition对象
2.       在获得锁的条件下,调用Condition的await方法释放锁并等待其他线程调用同一Condition对象的signal方法。
3.       另一线程在获得锁的条件下调用Condition对象的signal方法。

import java.util.concurrent.locks.Condition;

import java.util.concurrent.locks.ReentrantLock;

public class ConditionTest

{

    private static ReentrantLock locker = null;

    private static Condition condition = null;

    

    public static void main(String[] args) throws Exception

    {

        locker = new ReentrantLock();

        condition = locker.newCondition();

        

        Thread th = new Thread(new TestRunnable());

        th.start();

        

        Thread.sleep(3000);

        

        System.out.println("main: signal all.");

        // 调用condition.signalAll()将使Test线程中的阻塞结束。

        locker.lock();

        condition.signalAll();

        locker.unlock();

        

        System.out.println("main: end.");

    }

    

    private static class TestRunnable implements Runnable

    {

        @Override

        public void run()

        {

            locker.lock();

            try

            {

                System.out.println("test: before 'condition.await()'");

                

                // await()将阻塞直到其他线程调用condition.signal。

                condition.await();

                

                System.out.println("test: after 'condition.await()'");

                Thread.sleep(1000);

            }

            catch (InterruptedException e)

            {

            }

            finally 

            {

                locker.unlock();

            }

        }

    }

}

生产者与消费者示例

 

import java.util.LinkedList;

import java.util.Queue;

import java.util.concurrent.locks.Condition;

import java.util.concurrent.locks.ReentrantLock;

public class ConditionTest2

{

    private static ReentrantLock locker;

    private static Condition condition;

    private static Queue<Integer> queue;

    

    public static void main(String[] args) throws Exception

    {

        locker = new ReentrantLock();

        condition = locker.newCondition();

        queue = new LinkedList<Integer>();

        

        Thread pth = new ProducerThread();

        Thread cth = new ConsumerThread();

        

        pth.start();

        cth.start();

        

        Thread.sleep(30 * 1000);

        

        pth.interrupt();

        cth.interrupt();

        

        pth.join();

        cth.join();

    }

    

    

    private static class ProducerThread extends Thread

    {

        @Override

        public void run()

        {

            // 每0-500毫秒产生一个随机整数并加入队列。

            while (!Thread.currentThread().isInterrupted())

            {

                locker.lock();

                try

                {

                    int x = (int)(Math.random() * 100);

                    queue.offer(x);

                    condition.signalAll();

                    System.out.println("producer: " + x + ", signal all");

                    // 随机休眠0-499毫秒

                    Thread.sleep((int)(Math.random() * 500));

                }

                catch (InterruptedException e)

                {

                    break;

                }

                finally 

                {

                    locker.unlock();

                }

            }

            System.out.println("End of ProducerThread.");

        }

    }

    

    private static class ConsumerThread extends Thread

    {

        @Override

        public void run()

        {

            // 每0-500毫秒从队列取出一个数并输出。

            while (!Thread.currentThread().isInterrupted())

            {

                locker.lock();

                try

                {

                    // 如果队列为空,将等待ProducerThread向队列插入数据。

                    while (queue.isEmpty())

                    {

                        System.out.println("consumer: Queue is empty.");

                        condition.await();

                    }

                    int x  = queue.poll();

                    System.out.println("consumer: " + x);

                    

                    // 随机休眠0-499毫秒

                    Thread.sleep((int)(Math.random() * 500));

                }

                catch (InterruptedException e)

                {

                    break;

                }

                finally

                {

                    locker.unlock();

                }

            }

            System.out.println("End of ComsumerThread.");

        }

    }

}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java string signal