Java 多线程 竞争造成的异常

初始状态, 未使用线程同步机制,造成错误。

package com.kunpengku;

import java.util.Random;
import java.util.Stack;

public class Welcome {

    public static Stack<Integer> abc = new Stack();
    public static void main(String[] args) throws Exception
    {

        for (int i=0;i<10;i++){
            abc.push(i);
        }
        //多线程方式
        Q q = new Q();
        Q q2 = new Q();
        q.start();
        q2.start();

    }

}

class Q extends Thread{
    public static Stack<Integer> abc;

    Q(){
        this.abc = Welcome.abc;
    }

    public void run(){
        try{
            while(this.abc.size()>0){
                Random random = new Random();
                Thread.sleep(random.nextInt(1000));

                int tmp = abc.pop();
                System.out.println(Thread.currentThread() + String.valueOf(tmp));
            }
        }catch(InterruptedException e){
            e.printStackTrace();
        }

    }
}

终端输出

Thread[Thread-0,5,main]9
Thread[Thread-1,5,main]8
Thread[Thread-1,5,main]7
Thread[Thread-0,5,main]6
Thread[Thread-1,5,main]5
Thread[Thread-0,5,main]4
Thread[Thread-1,5,main]3
Thread[Thread-1,5,main]2
Thread[Thread-0,5,main]1
Thread[Thread-1,5,main]0
Exception in thread "Thread-0" java.util.EmptyStackException
    at java.util.Stack.peek(Unknown Source)
    at java.util.Stack.pop(Unknown Source)
    at com.kunpengku.Q.run(Welcome.java:38)

解决方法 利用Lock 线程锁

package com.kunpengku;

import java.util.Random;
import java.util.Stack;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Welcome {

    public static Stack<Integer> abc = new Stack();
    public static void main(String[] args) throws Exception
    {

        for (int i=0;i<10;i++){
            abc.push(i);
        }
        //多线程方式二
        Q q = new Q();
        Q q2 = new Q();
        q.start();
        q2.start();

    }

}

class Q extends Thread{
    public static Stack<Integer> abc;

    private static Lock lock = new ReentrantLock();
    Q(){
        this.abc = Welcome.abc;
    }

    public void run(){
        lock.lock();
        try{
            while(this.abc.size()>0){
                Random random = new Random();
                Thread.sleep(random.nextInt(1000));

                int tmp = abc.pop();
                System.out.println(Thread.currentThread() + String.valueOf(tmp));
            }
        }catch(InterruptedException e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }

    }
}

主要增加了 30, 36, 48行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值