synchronized :
将 方法标记为synchronized,如果莫个任务处于一个被标记为synchronized的方法调用中,则在这个线程从该方法返回前,其他类要调用此方法都将受到阻塞
synchronized void f();
在使用并发时,将域设置为private是非常重要的,否则synchronized就不能防止其他任务直接访问域
应该什么时候同步:
一个变量可能被另一个线程读取,或者正在读取一个上次已经被另一个线程写过的变量,那么必须同步
××××××× 每个访问临界共享资源的方法都必须被同步
不正确的访问,在Java中,递增不是原子性的操作,因此不保护可能在只进行了一个自加操作next就被调用 (概率很低)
package Number_2102;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* 使用 synchronized 实现同步化 保护数据域
*
* @author he
*
*/
abstract class Ingenerator {
abstract int next1();
abstract int next2();
}
class EvenChecker implements Runnable {
public Ingenerator ingenerator;
public EvenChecker(Ingenerator ing) {
ingenerator = ing;
}
public void run() {
int i = 100;
int val = ingenerator.next1();
int val2 = ingenerator.next2();
while (i-- > 0) {
if (val % 2 == 0) {
System.out.println(" synchronized " + val);
}
if (val2 % 2 == 0) {
System.out.println(" no synchronized " + val2);
}
}
}
// 测试 创建多个线程
public static void test(Ingenerator ing, int i) {
ExecutorService eService = Executors.newCachedThreadPool();
for (int k = 0; k < i; k++) {
eService.execute(new EvenChecker(ing));
}
eService.shutdown();
}
}
public class P678 extends Ingenerator {
private int count = 0;
@Override
// 用sychronized修饰
synchronized int next1() {
++count;
// Thread.yield();
++count;
return count;
}
int next2() {
++count;
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
++count;
return count;
}
public static void main(String[] args) {
EvenChecker.test(new P678(), 5);
}
}
什么是原子性操作?
除了long 和double 类型的基本来行的赋值和返回操作 。
原子操作:
1. 不能被线程调度机制中断的操作
2. 一旦操作那么一定可以在切换线程之前执行完毕
由于可视性,缺少同步使得原子操作可以在处于不稳定的中间状态时被读取
volatile 关键字 可以让long和double变量获取原子性
同时 volatile关键字还确保了可视性
在非volatile域上的原子操作不必刷新到主存中去因此其它任务看不到新值
如果多个任务同时访问莫个域则应该是volatile的
volatile使用的限制 :
1.一个域的值不能依靠之前的值 (如递增计数器)
2.一个域不能受到其他域的限制
package Number_2102;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 原子性,和易变性 原子操作: 除了long和double类型的基本类型的赋值和返回 非volatile的原子操作不惜刷新到主存中 所以还有刷新的问题
*
* @author he
*
*/
public class P682 implements Runnable {
private static int i;
public static void en() {
i++;
i++;
}
public synchronized static int get() {
return i;
}
public void run() {
// TODO Auto-generated method stub
while (true) {
en();
}
}
public static void main(String[] args) {
ExecutorService eService = Executors.newCachedThreadPool();
P682 p = new P682();
eService.execute(p);
while (true) {
int val = p.get();
if (val % 2 != 0) {
System.out.println(val);
System.exit(0);
}
}
}
}
虽然get进行了同步化 ,return 是原子操作 但是仍能获取一个奇数
修改如下 即可 注意 如果要对一个静态数据进行同步化 用 synchronized static 并且 每个与该数据有关的方法都要用synchronized static
package Number_2102;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 原子性,和易变性 原子操作: 除了long和double类型的基本类型的赋值和返回 非volatile的原子操作不惜刷新到主存中 所以还有刷新的问题
*
* @author he
*
*/
public class P682 implements Runnable {
private volatile static int i;
public synchronized static void en() {
i++;
i++;
}
public synchronized static int get() {
return i;
}
public void run() {
// TODO Auto-generated method stub
while (true) {
en();
}
}
public static void main(String[] args) {
ExecutorService eService = Executors.newCachedThreadPool();
P682 p = new P682();
eService.execute(p);
while (true) {
int val = p.get();
if (val % 2 != 0) {
System.out.println(val);
System.exit(0);
}
}
}
}
原子类: JavaSE5 引入了 AtomicInteger、AtomicLong、AtomicReference 等原子性变量类 在机器级别上实现原子性
主要用于调优
临界区:
synchronized(syncObject) ------> syncObject指定对象 一般为this
{ //code
}
如何把一个非保护类型的类在其他类的保护和控制下应用于多线程的环境
package Number_2102;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 使用同步控制块,可以使多个任务访问对象的时间性能显著提高
*
* 把非保护类型的类,在其他类的保护和控制下应用于多个线程的环境
*
* @author he
*
*/
// 不受保护的类
class Pair {
private int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public Pair() {
this(0, 0);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void incrementX() {
x++;
}
public void incrementY() {
y++;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "x:" + x + " , y:" + y;
}
// 定义runtime 异常
class PairValueNotException extends RuntimeException {
public PairValueNotException() {
super("Pair values not equal: " + Pair.this);
}
}
public void checkState() {
if (x != y) {
throw new PairValueNotException();
}
}
}
// 受保护的类 在这里调用不受保护的类Pair
abstract class PairManger {
// 原子类
AtomicInteger checkCounter = new AtomicInteger();
protected Pair p = new Pair();
// 返回支持线程同步的List
private List<Pair> storage = Collections.synchronizedList(new ArrayList<Pair>());
public synchronized Pair getPair() {
return new Pair(p.getX(), p.getY());
}
protected void stor(Pair p) {
storage.add(p);
try {
TimeUnit.MILLISECONDS.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 抽象方法 用时再进行线程同步控制
abstract void increment();
}
class PairManger1 extends PairManger {
@Override
// 线程同步控制
synchronized void increment() {
p.incrementX();
p.incrementY();
stor(getPair());
}
}
class PairManger2 extends PairManger {
@Override
void increment() {
Pair temp;
// 同步控制块
synchronized (this) {
p.incrementX();
p.incrementY();
temp = getPair();
}
stor(temp);
}
}
class PairManipulator implements Runnable {
PairManger pm;
public PairManipulator(PairManger pm) {
this.pm = pm;
}
public void run() {
while (true) {
pm.increment();
}
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "Pair" + pm.getPair() + " checkCounter " + pm.checkCounter.get();
}
}
// 统计频度
class PairCheck implements Runnable {
PairManger pm;
public PairCheck(PairManger pm) {
this.pm = pm;
}
public void run() {
while (true) {
// 以原子方式将checkCounter加1
pm.checkCounter.incrementAndGet();
pm.getPair().checkState();
}
}
}
public class P686 {
static void test(PairManger pm1, PairManger pm2) {
ExecutorService eService = Executors.newCachedThreadPool();
PairManipulator pp1 = new PairManipulator(pm1);
PairManipulator pp2 = new PairManipulator(pm2);
PairCheck pc1 = new PairCheck(pm1);
PairCheck pc2 = new PairCheck(pm2);
eService.execute(pp1);
eService.execute(pp2);
eService.execute(pc1);
eService.execute(pc2);
try {
TimeUnit.MILLISECONDS.sleep(200);
} catch (Exception e) {
System.out.println("sleep interruoted");
}
System.out.println("pp1: " + pp1 + "\npp2: " + pp2);
System.exit(0);
}
public static void main(String[] args) {
PairManger pm1 = new PairManger1();
PairManger pm2 = new PairManger2();
test(pm1, pm2);
}
}
在其他对象上进行同步
package Number_2102;
/**
* 在其他对象上同步
*
* @author he
*
*/
class DuslSynch implements Runnable {
private Object syncObject = new Object();
synchronized static void f() {
for (int i = 0; i < 5; i++) {
System.out.println("f()");
Thread.yield();
}
}
void g() {
synchronized (syncObject) { // 在syncObject上进行同步控制
for (int i = 0; i < 5; i++) {
System.out.println("g()");
Thread.yield();
}
}
}
public void run() {
f();
}
}
public class P689 {
public static void main(String[] args) {
final DuslSynch ds = new DuslSynch();
new Thread(ds).start();
ds.g();
}
}