练气期(并发编程基础)
练气期一层(this)
synchronized(this)和synchronized方法都是锁当前对象。
public class Test_01 {
private int count = 0; // 存在堆中
private Object o = new Object(); // 存在堆中
// 多个线程都能找到的,都能访问的对象叫临界资源对象
public void testSync1() {
synchronized (o) {
System.out.println(Thread.currentThread().getName()
+ " count = " + count++);
}
}
public void testSync2() {
synchronized (this) {
System.out.println(Thread.currentThread().getName()
+ " count = " + count++);
}
}
public synchronized void testSync3() {
System.out.println(Thread.currentThread().getName()
+ " count = " + count++);
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
final Test_01 t = new Test_01();
new Thread(new Runnable() {
@Override
public void run() {
t.testSync3();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
t.testSync3();
}
}).start();
}
}
练气期二层(static)
静态同步方法,锁的是当前类型的类对象。
public class Test_02 {
private static int staticCount = 0;
public static synchronized void testSync4(){
System.out.println(Thread.currentThread().getName()
+ " staticCount = " + staticCount++);
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void testSync5(){
synchronized(Test_02.class){
System.out.println(Thread.currentThread().getName()
+ " staticCount = " + staticCount++);
}
}
}
练气期三层(原子性)
加锁的目的就是为了保证操作的原子性
public class Test_03 implements Runnable {
private int count = 0;
@Override
public /*synchronized*/ void run() {
System.out.println(Thread.currentThread().getName()
+ " count = " + count++);
}
public static void main(String[] args) {
Test_03 t = new Test_03();
for (int i = 0; i < 5; i++) {
new Thread(t, "Thread - " + i).start();
}
}
}
练气期四层(同步与非同步方法间调用)
同步方法只影响锁定同一个锁对象的同步方法。不影响其他线程调用非同步方法,或调用其他锁资源的同步方法。
public class Test_04 {
Object o = new Object();
public synchronized void m1() { // 重量级的访问操作。
System.out.println("public synchronized void m1() start");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("public synchronized void m1() end");
}
public void m3() {
synchronized (o) {
System.out.println("public void m3() start");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("public void m3() end");
}
}
public void m2() {
System.out.println("public void m2() start");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("public void m2() end");
}
public static class MyThread01 implements Runnable {
public MyThread01(int i, Test_04 t) {
this.i = i;
this.t = t;
}
int i;
Test_04 t;
public void run() {
if (i == 0) {
t.m1();
} else if (i > 0) {
t.m2();
} else {
t.m3();
}
}
}
public static void main(String[] args) {
Test_04 t = new Test_04();
new Thread(new Test_04.MyThread01(0, t)).start();
new Thread(new Test_04.MyThread01(1, t)).start();
new Thread(new Test_04.MyThread01(-1, t)).start();
}
}
练气期五层(存在原子性问题)
同步方法只能保证当前方法的原子性,不能保证多个业务方法之间的互相访问的原子性。一般来说,商业项目中,不考虑业务逻辑上的脏读问题。如你买东西下订单后,提示订单已下,查询时候,可能看不到。一般我们只关注数据脏读。但是在金融领域,保险领域严格要求。
public class Test_05 {
private double d = 0.0;
public synchronized void m1(double d){
try {
// 相当于复杂的业务逻辑代码。
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.d = d;
}
public double m2(){
return this.d;
}
public static void main(String[] args) {
final Test_05 t = new Test_05();
new Thread(new Runnable() {
@Override
public void run() {
t.m1(100);
}
}).start();
System.out.println(t.m2());
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.m2());
}
}
练气期六层(锁可重入)
同一个线程,多次调用同步代码,锁定同一个锁对象,可重入。
public class Test_06 {
synchronized void m1(){ // 锁this
System.out.println("m1 start");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
m2();
System.out.println("m1 end");
}
synchronized void m2(){ // 锁this
System.out.println("m2 start");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("m2 end");
}
public static void main(String[] args) {
new Test_06().m1();
}
}
练气期七层(调用父类的同步方法)
子类同步方法覆盖父类同步方法,可以指定调用父类的同步方法, 相当于锁的重入。父类的方法 <<==>> 本类的方法
public class Test_07 {
synchronized void m() {
System.out.println("Super Class m start");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Super Class m end");
}
public static void main(String[] args) {
new Sub_Test_07().m();
}
}
class Sub_Test_07 extends Test_07 {
synchronized void m() {
System.out.println("Sub Class m start");
super.m();
System.out.println("Sub Class m end");
}
}
练气期八层(锁与异常)
当同步方法中发生异常的时候,自动释放锁资源,不会影响其他线程的执行。我们需要注意的是在同步业务逻辑中,如果发生异常如何处理——— try/catch 。如存钱时,发送网络中断,查询的时候查到多少钱,存的钱要返还
public class Test_08 {
int i = 0;
synchronized void m() {
System.out.println(Thread.currentThread().getName() + " - start");
while (true) {
i++;
System.out.println(Thread.currentThread().getName() + " - " + i);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*if(i == 5){
i = 1/0;
}*/
//模拟存钱,中断处理
if (i == 5) {
try {
i = 1 / 0;
} catch (Exception e) {
i = 0;
}
}
}
}
public static void main(String[] args) {
final Test_08 t = new Test_08();
// 锁的是当前对象
new Thread(new Runnable() {
@Override
public void run() {
t.m();
}
}, "t1").start();
new Thread(new Runnable() {
@Override
public void run() {
t.m();
}
}, "t2").start();
}
}
练气期九层(volatile)
cpu默认查询cpu的高速缓存区域,CPU中每一个核都有自己的缓存,当cpu有中断的时候,他可能清空高速缓存区域数据,重新从内存中读取数据。volatile改变内存中的数据,通知底层OS系统,每次使用b的时候,最好看下内存数据是否发生变动。即volatile做的是一个通知OS系统的作。
public class Test_09 {
volatile boolean b = true; //线程可见性问题
void m(){
System.out.println("start");
while(b){}
System.out.println("end");
}
public static void main(String[] args) {
final Test_09 t = new Test_09();
new Thread(new Runnable() {
@Override
public void run() {
t.m();
}
}).start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.b = false; //堆空间的对象,线程共享
}
}
volatile的非原子性问题,只能保证可见性,不能保证原子性。
那什么时候使用volatile?棋牌室的人数,新增的人有一个线程去+1。这是可以使用volatile
join()多个线程在运行结束时,我把多个线程再main线程的位置连在一起,当其他线程都结束,即保证在所有线程循环执行+1后,再执行main线程打印。
public class Test_10 {
volatile int count = 0;
/*synchronized*/ void m() { //保证原子性的解决方法是使用synchronized或者是Atomic
for (int i = 0; i < 10000; i++) {
count++;
}
}
public static void main(String[] args) {
final Test_10 t = new Test_10();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10; i++) {
threads.add(new Thread(new Runnable() {
@Override
public void run() {
t.m();
}
}));
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(t.count); //理论上是10w。实际少于这个数
}
}
练气期十层(AtomicXxx)
什么时候有原子性,没有可见性?
*答:所谓原子性是指多个线程访问一个变量时,其结果必须保证正确性。*所谓可见性是指多线程间可以看最终结果的变量
public class Test_11 {
AtomicInteger count = new AtomicInteger(0);
void m() {
for (int i = 0; i < 10000; i++) {
/*if(count.get() < 1000)*/
count.incrementAndGet(); //相当于++count,count.getAndAccumulate()是count++;
}
}
public static void main(String[] args) {
final Test_11 t = new Test_11();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10; i++) {
threads.add(new Thread(new Runnable() {
@Override
public void run() {
t.m();
}
}));
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(t.count.intValue());
}
}
练气期十一层(锁对象变更)
- 同步代码一旦加锁后,那么会有一个临时的锁引用指向锁对象,和真实的引用无直接关联。在锁未释放之前,修改锁引用,不会影响同步代码的执行。
- 我们打印的是Test_13中的o。不是锁引用的_O;下面synchronized锁的是两个对象。打印的是同一个对象。
public class Test_13 {
Object o = new Object(); //变量引用
int i = 0;
int a() {
try {
/*
* return i ->
* int _returnValue = i; // 0;
* return _returnValue;
*/
return i;
} finally {
i = 10;
}
}
void m() {
System.out.println(Thread.currentThread().getName() + " start");
synchronized (o) { //计算变量引用与变量引用不是一回事
while (true) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " - " + o);
}
}
}
public static void main(String[] args) {
final Test_13 t = new Test_13();
new Thread(new Runnable() {
@Override
public void run() {
t.m();
}
}, "thread1").start();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
t.m();
}
}, "thread2");
t.o = new Object();
thread2.start(); //更改临界资源对象
System.out.println(t.i);
System.out.println(t.a());
System.out.println(t.i);
}
}
练气期十二层(CountDownLatch)
- 不会进入等待队列,可以和锁混合使用,或替代锁的功能。
- 一次性在门上挂多个锁。
- 作用如:init对象的时候有一个前后顺序的问题。
public class Test_15 {
CountDownLatch latch = new CountDownLatch(5);
void m1() {
try {
latch.await();// 等待门闩开放。
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("m1() method");
}
void m2() {
for (int i = 0; i < 10; i++) {
if (latch.getCount() != 0) {
System.out.println("latch count : " + latch.getCount());
latch.countDown(); // 减门闩上的锁。
}
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("m2() method : " + i);
}
}
public static void main(String[] args) {
final Test_15 t = new Test_15();
new Thread(new Runnable() {
@Override
public void run() {
t.m1();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
t.m2();
}
}).start();
}
}
练气期大圆满
public class Test_14 {
String s1 = "hello";
String s2 = new String("hello"); // new关键字,一定是在堆中创建一个新的对象。
Integer i1 = 1; // i1与i2是同一个变量,在常量池中,new是放在堆内存
Integer i2 = 1;
void m1() {
synchronized (i1) { //s1与s2
System.out.println("m1()");
while (true) {
}
}
}
void m2() {
synchronized (i2) {
System.out.println("m2()");
while (true) {
}
}
}
public static void main(String[] args) {
final Test_14 t = new Test_14();
new Thread(new Runnable() {
@Override
public void run() {
t.m1();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
t.m2();
}
}).start();
}
}
自定义容器,提供新增元素(add)和获取元素数量(size)方法。启动两个线程。线程1向容器中新增10个数据。线程2监听容器元素数量,当容器元素数量为5时,线程2输出信息并终止。
- 使用volatile
public class Test_01 {
public static void main(String[] args) {
final Test_01_Container t = new Test_01_Container();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("add Object to Container " + i);
t.add(new Object());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (t.size() == 5) {
System.out.println("size = 5");
break;
}
}
}
}).start();
}
}
class Test_01_Container {
volatile List<Object> container = new ArrayList<>();
public void add(Object o) {
this.container.add(o);
}
public int size() {
return this.container.size();
}
}
- 使用synchronized和wait(), 调用wait()将释放锁,并且进入等待队列中,生产者与消费者模型
public class Test_02 {
public static void main(String[] args) {
final Test_02_Container t = new Test_02_Container();
final Object lock = new Object();
new Thread(new Runnable(){
@Override
public void run() {
synchronized (lock) {
if(t.size() != 5){
try {
lock.wait(); // 线程进入等待队列。
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("size = 5");
lock.notifyAll(); // 唤醒其他等待线程
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
for(int i = 0; i < 10; i++){
System.out.println("add Object to Container " + i);
t.add(new Object());
if(t.size() == 5){
lock.notifyAll();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
}
class Test_02_Container{
List<Object> container = new ArrayList<>();
public void add(Object o){
this.container.add(o);
}
public int size(){
return this.container.size();
}
}
- 使用门闩避免进入等待队列,效率更高。
public class Test_03 {
public static void main(String[] args) {
final Test_03_Container t = new Test_03_Container();
final CountDownLatch latch = new CountDownLatch(1);
new Thread(new Runnable(){
@Override
public void run() {
if(t.size() != 5){
try {
latch.await(); // 等待门闩的开放。 不是进入等待队列
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("size = 5");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 10; i++){
System.out.println("add Object to Container " + i);
t.add(new Object());
if(t.size() == 5){
latch.countDown(); // 门闩-1
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
class Test_03_Container{
List<Object> container = new ArrayList<>();
public void add(Object o){
this.container.add(o);
}
public int size(){
return this.container.size();
}
}