Java多线程之wait和notify

本文介绍了一种使用四个线程向字符数组按顺序输出ABCD的多线程同步方法,并提供了使用wait和notify、sleep及CountDownLatch实现的具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:有4个线程和1个公共的字符数组。线程1的功能就是向数组输出A,线程2的功能就是向字符输出B,线程3的功能就是向数组输出C,线程4的功能就是向数组输出D。要求按顺序向数组赋值ABCDABCDABCD,ABCD的个数由线程函数1的参数指定。

本文通过wait和notify实现、sleep、CountDownLatch实现。

wait():等待,如果线程执行了wait方法,那么该线程会进入等待的状态,等待状态下的线程必须要被其他线程调用notify()方法才能唤醒。
notify():唤醒,唤醒线程池等待线程其中的一个。
notifyAll():唤醒线程池所有等待线程。

wait与notify方法要注意的事项:

  1. wait方法与notify方法是属于Object对象的。
  2. wait方法与notify方法必须要在同步代码块或者是同步函数中才能使用。
  3. wait方法与notify方法必须要由所对象调用。

wait和notify实现代码示例:

public class ThreadABCDTest extends Thread {
    private static String rs;
    private static Lock lock = new ReentrantLock();
    private static int state = 0;
    private static Object objLock = new Object();//主线程等待子线程的同步唤醒

    public static String multiThreadWrite(final int times) {
        rs = new String();

        Thread threadA = new Thread()
        {
            public void run(){
                int count = 0;
                while(count<times)
                {
                    lock.lock();
                    if(state%4==0)
                    {
                        rs += "A";
                        state++;
                        count++;
                    }
                    lock.unlock();
                }
            }
        };


        Thread threadB = new Thread()
        {

            public void run(){
                int count = 0;
                while(count<times)
                {
                    lock.lock();
                    if(state%4==1)
                    {
                        rs += "B";
                        state++;
                        count++;
                    }
                    lock.unlock();
                }
            }
        };

        Thread threadC = new Thread()
        {
            public void run(){
                int count=0;
                while(count<times)
                {
                    lock.lock();
                    if(state%4==2)
                    {
                        rs += "C";
                        state++;
                        count++;
                    }
                    lock.unlock();
                }
            }
        };

        Thread threadD =new Thread()
        {
            public void run()
            {
                int count =0;
                while(count<times)
                {
                    lock.lock();
                    if(state%4==3)
                    {
                        rs += "D";
                        state++;
                        count++;
                    }
                    lock.unlock();
                }
                synchronized (objLock) {
                    objLock.notify();//子线程唤醒
                }
            }
        };

        threadA.start();
        threadB.start();
        threadC.start();
        threadD.start();
        synchronized (objLock) {
            try {
                objLock.wait();//主线程等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return rs;
    }

    public static void main(String[] args) {
        String rs = ThreadABCDTest.multiThreadWrite(5);
        System.out.println(rs);
    }
}

sleep代码示例:

public class ThreadABCD2 extends Thread{
    private static String result ;
    private static Lock lock = new ReentrantLock();
    private static int state = 0;

    public static String multiThreadWrite(final int times) {
        result = new String();

        Thread threadA = new Thread()
        {
            public void run(){
                int count = 0;
                while(count<times)
                {
                    lock.lock();
                    if(state%4==0)
                    {
                        result += "A";
                        state++;
                        count++;
                    }
                    lock.unlock();
                }
            }
        };


        Thread threadB = new Thread()
        {

            public void run(){
                int count = 0;

                while(count<times)
                {
                    lock.lock();
                    if(state%4==1)
                    {
                        result += "B";
                        state++;
                        count++;
                    }
                    lock.unlock();
                }
            }
        };

        Thread threadC = new Thread()
        {
            public void run(){
                int count=0;

                while(count<times)
                {
                    lock.lock();
                    if(state%4==2)
                    {
                        result += "C";
                        state++;
                        count++;
                    }
                    lock.unlock();
                }
            }
        };

        Thread threadD =new Thread()
        {
            public void run()
            {
                int count =0;
                while(count<times)
                {
                    lock.lock();
                    if(state%4==3)
                    {
                        result += "D";
                        state++;
                        count++;
                    }
                    lock.unlock();
                }
            }
        };

        threadA.start();
        threadB.start();
        threadC.start();
        threadD.start();
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        String rs = ThreadABCD2.multiThreadWrite(2);
        System.out.println(rs);
    }
}

CountDownLatch代码示例:

public class ThreadABCD extends Thread{
    private static String result ;
    private static Lock lock = new ReentrantLock();
    private static int state = 0;
    //static boolean flag;
    private static final CountDownLatch latch = new CountDownLatch(4);

    public static String multiThreadWrite(final int times) {
        result = new String();
        //flag = false;

        Thread threadA = new Thread()
        {
            public void run(){
                int count = 0;
                while(count<times)
                {
                    lock.lock();
                    if(state%4==0)
                    {
                        result += "A";
                        state++;
                        count++;
                    }
                    lock.unlock();
                }
                latch.countDown();
            }
        };


        Thread threadB = new Thread()
        {

            public void run(){
                int count = 0;

                while(count<times)
                {
                    lock.lock();
                    if(state%4==1)
                    {
                        result += "B";
                        state++;
                        count++;
                    }
                    lock.unlock();
                }
                latch.countDown();
            }
        };

        Thread threadC = new Thread()
        {
            public void run(){
                int count=0;

                while(count<times)
                {
                    lock.lock();
                    if(state%4==2)
                    {
                        result += "C";
                        state++;
                        count++;
                    }
                    lock.unlock();
                }
                latch.countDown();
            }
        };

        Thread threadD =new Thread()
        {
            public void run()
            {
                int count =0;
                while(count<times)
                {
                    lock.lock();
                    if(state%4==3)
                    {
                        result += "D";
                        state++;
                        count++;
                    }
                    lock.unlock();
                }
                //flag=true;
                latch.countDown();
            }
        };

        threadA.start();
        threadB.start();
        threadC.start();
        threadD.start();
//        try {
//            Thread.sleep(1000L);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        String rs = ThreadABCD.multiThreadWrite(2);
        System.out.println(rs);
    }
}

以上三种方式的结果一样,结果如下:

ABCDABCD

Process finished with exit code 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值