package com.interview.threads.teststructor;
import java.util.Vector;
/**
* @author helloLi
* @version 1.0
* @date 2021/3/1 23:17
* 一个存一个取也是一种线程是否安全的测试方法
*/
public class VectorSynTest {
private static Vector<Integer> vector = new Vector<>();
private static int gf = 0;
private static int mk = 0;
public static void main(String[] args) throws InterruptedException {
for(int j = 0; j < 50000; j++) {
Thread removedThread = new Thread(new Runnable() {
@Override
public void run() {
for(int l = 0; l < 2 ; l++){
vector.add(1);
mk++;
try {
int increase = increase();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("--------------------------------------------");
System.out.println("vector加20000次:"+vector.size());
System.out.println("普通变量加20000次+------:"+mk);
System.out.println("加锁i++加20000次" + gf);
System.out.println("---------------------------------------------");
}
});
removedThread.start();
}
for(int j = 0; j < 50000; j++) {
Thread printThread = new Thread(new Runnable() {
@Override
public void run() {
for(int l = 0; l< 2 ; l++){
vector.add(1);
mk++;
try {
int increase2 = increase();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("--------------------------------------------");
System.out.println("vector加20000次:"+vector.size());
System.out.println("普通变量加20000次+------:"+mk);
System.out.println("加锁i++加20000次" + gf);
System.out.println("---------------------------------------------");
}
});
printThread.start();
}
}
public static synchronized int increase() throws InterruptedException {
System.out.println("我是加锁的累加方法,我叫"+Thread.currentThread().getName());
gf++;
System.out.println(Thread.currentThread().getName()+"线程运行结束!");
return gf;
}
public static synchronized int decrease() throws InterruptedException {
System.out.println("我是加锁的递减方法,我叫"+Thread.currentThread().getName());
gf--;
System.out.println(Thread.currentThread().getName()+"线程运行结束!");
return gf;
}
}
代码初步验证集合中的Vector的多线程安全性
最新推荐文章于 2021-08-15 13:13:41 发布