初始状态, 未使用线程同步机制,造成错误。
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行。