线程的安全性问题解决:
voliate只能是可见性 ;AtomicInteger只能是原子的;
Lock接口
Lock接口的实现类和方法:
多个线程并发拿锁抢占资源是无法终断的使用这个方法可以中断。
tryLock是非阻塞的获取锁。
公平和非公平锁。
看其实现类:
public ReentrantLock() {
sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
看构造方法,默认是非公平的。
package com.roocon.thread.t9;
public class SequenceNotSafe {
private int value;
public int getNext() {
int a = value ++;
return a;
}
public static void main(String[] args) {
Sequence s = new Sequence();
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName() + " " + s.getNext());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName() + " " + s.getNext());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName() + " " + s.getNext());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
解决加ReentrantLock()
这样写是不对的要所有的线程共用一把lock才可以。
加锁的:
package com.roocon.thread.t9;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Sequence {
private int value;
Lock lock = new ReentrantLock();
Lock l1 = new ReentrantLock();
/**
* @return
*/
public int getNext() {
lock.lock();
int a = value ++;
lock.unlock();
return a;
}
public static void main(String[] args) {
Sequence s = new Sequence();
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName() + " " + s.getNext());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName() + " " + s.getNext());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName() + " " + s.getNext());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
Lock也会用到synchronized,不要重复的造轮子。
---------------t9------------
补充:
tryLock:https://blog.csdn.net/michaelgo/article/details/81481068
lockInterruptibly:https://blog.csdn.net/yyd19921214/article/details/49737061