门
package com.dwz.concurrency2.chapter6; /** * SharedResource */ public class Gate { private int counter = 0; private String name = "Nobody"; private String address = "Nowhere"; /** * 临界值 * @param name * @param address * synchronized * * 将数据的读写都加在一个锁里面,极大影响程序执行效率,怎样优化? */ public void pass(String name, String address) { this.counter++; /*race*/ this.name = name; this.address = address; verify(); } public void verify() { if(this.name.charAt(0) != this.address.charAt(0)) { System.out.println("***********BROKEN*************" + toString()); } } @Override public String toString() { return "No." + counter + ":" + name + "," + address; } }
过门人
package com.dwz.concurrency2.chapter6; public class User extends Thread { private final String myName; private final String myAddress; private final Gate gate; public User(String myName, String myAddress, Gate gate) { super(); this.myName = myName; this.myAddress = myAddress; this.gate = gate; } @Override public void run() { System.out.println(myName + " BEGIN"); while(true) { this.gate.pass(myName, myAddress); } } }
测试代码
package com.dwz.concurrency2.chapter6; public class Client { public static void main(String[] args) { Gate gate = new Gate(); User bj = new User("beilao", "beijing", gate); User sh = new User("shanglao", "shanghai", gate); User gz = new User("guanglao", "guangzhou", gate); bj.start(); sh.start(); gz.start(); } }
测试结果:不是线程安全的,当pass()上加synchronized时线程安全
但是将数据的读写都加在一个锁里面,极大影响程序执行效率,怎样优化?