首页 文章 精选 留言 我的

精选列表

搜索[基础],共10000篇文章
优秀的个人博客,低调大师

C++程序设计基础(4)宏定义和内联

1.知识点 1.1宏定义 (1)不带参数的宏定义 1 #define ERROR_MESSAGE -100 2 #define SECONDS_PER_DAY 60*60*60 (2)带参数宏定义,这种形式称为宏函数,但其实并不是函数 #define OUTPUTINT(x) cout<<"INT:"<<x<<endl #define OUTPUTCHAR cout<<"CHAR:"<<x<<endl 1.2内联函数 宏定义是在预处理阶段进行宏展开的,但是经常会出现一些意想不到的错误,故出现内联函数,内联函数既发挥了宏定义的优势,又弥补了其缺点。 内联函数是在定义时在函数最前面加上inline,或者将函数声明的同时进行定义(这种方式不推荐)。 下面是一个内联函数的例子: 1 class Rectangle { 2 public: 3 Rectangle(int, int); 4 int getSquare(); 5 int getGirth() { return 2 * (length, width); } //直接在声明时定义函数,形成内联函数 6 private: 7 int length; 8 int width; 9 }; 10 11 Rectangle::Rectangle(int l,int w):length(l),width(w){} 12 inline int Rectangle::getSquare() { //在函数定义时使用inline形成内联函数 13 return length * width; 14 } 2.面试题 2.1简述内联函数和宏定义的区别 相同点:二者都能够节省频繁的函数调用过程中所产生的时间和空间消耗,提高执行的效率;二者都是哦谈过将函数调用替换成完整的函数体,二者的实现也类似。 区别:(1)二者的根本区别在于宏定义仅仅是字符串的替换,并不是函数,而内联函数是函数。 (2)二者的代码展开发生在不同阶段,宏定义是在预处理阶段展开的,而内联函数是在编译阶段展开的。 (3)内联函数作为类的成员函数时,可以访问类的所有成员,包括公有、私有、保护成员,隐式使用this指针,而宏定义无法实现这些功能。 (4)内联函数可以完全替代宏定义,故尽量少使用宏定义。 (5)另外在使用内联函数时要注意代码膨胀问题,内联函数应该尽量简短(另外现在编译器一般都有优化功能,当检测到内联函数代码很长时,不会进行内联,即使使用了内联函数)。 2.2宏定义的宏展开错误 指出下面程序中宏定义的错误并修改 1 #define MAX(a,b) a>b?a:b 2 #define MUL(a,b) a*b 3 int main(int argc, char *argv[]) { 4 int x = 4, y = 2; 5 int max = MAX(x, y); 6 int product = MUL(x, y); 7 cout << "the max is " << max << endl; 8 cout << "the product is " << product << endl; 9 getchar(); 10 return 0; 11 } 知识点:宏定义自身缺陷主要是宏展开之后,由于运算符的优先级等原因,使得宏定义展开后的语义和预想的发生偏差。 以下时两个宏展开出错的例子 1 int product=MUL(x,y+3) 2 int max=MAX(x,y)+2 3 4 //本意是 5 int product=x*(y+3) 6 int max=(x>y?x:y)+2 7 //实际宏展开变成了 8 int product=x*y+3 9 int max=x>y?x:y+2 解决办法包括以下两点: (1)给参数自身加上括号 (2)给整个宏定义加上括号 其修改结果如下: #define MAX(a,b) ((a)>(b)?(a):(b)) #define MUL(a,b) ((a)*(b)) 2.3内联函数的常识性问题 下列关于内联函数描述错误的是 (A)内联函数可以被重载; (B)构造函数可以被定义成内联函数; (C)内联函数能够减少函数调用的开销; (D)内联函数应该在函数声明时使用inline关键字 答案:D,一定要在定义时使用inline,在声明时使用不会起到任何作用。

优秀的个人博客,低调大师

java基础巩固-浅析String源码及其不可变性

字符串可以说是广泛应用在日常编程中,jdk从1.0就提供了String类来创建和操作字符串。同时它也是不可改变类(基本类型的包装类都不可改变)的典型代表。 源码查看(基于1.8) public final class String implements java.io.Serializable, Comparable<String>, CharSequence { private final char value[]; //这边只是引用并不是真正对象 ... } //首先string类创建的对象是不可变的(一个对象在创建完成后不能再改变它状态,说明是不可变的,并发程序最喜欢不可变量了), //里面最主要的成员为char类型的数组 几个构造方法 //空的构造方法 例如 String a = new String(); a为""空字符 public String() { this.value = new char[0]; } //带参构造方法 将源的hash和value赋给目标String public String(String original) { this.value = original.value; this.hash = original.hash; } 几个常用经典的String类方法 1.equals //如果引用指向的内存值都相等 直接返回true public boolean equals(Object anObject) { if (this == anObject) { return true; } //instanceof判断是否属于或子类 但Stringfinal修饰不可继承 只考虑是否为String类型 //上面说过String的成员为char数组,equals内则比较char类数组元素是否一一相等 if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; //长度不相等返回false if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; //从后往前单个字符判断,如果有不相等,返回false while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; } 2.subString(beginIndex,endIndex) subString这边存在一个小插曲 在jdk1.7以前,该方法存在内存泄漏问题。之所以存在是因为在此之前,String三个参数的构造方法是这么写的。成员变量为这三个,jdk7以后取消掉了offset和count加入了hash,虽然原来的构造方法简洁高效但存在gc问题。所以7以后放弃了性能采取了更为保守的写法。 /** The value is used for character storage. */ private final char value[]; /** The offset is the first index of the storage that is used. */ private final int offset; /** The count is the number of characters in the String. */ private final int count; ... public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > count) { throw new StringIndexOutOfBoundsException(endIndex); } if (beginIndex > endIndex) { throw new StringIndexOutOfBoundsException(endIndex - beginIndex); } //虽然这边返回的是新的String对象,但构造方法中还引用着原先的value return ((beginIndex == 0) && (endIndex == count)) ? this : new String(offset + beginIndex, endIndex - beginIndex, value); } ... String(int offset, int count, char value[]) { this.value = value; this.offset = offset; this.count = count; } //这边开始this.value = value; 出现问题,这三个个原来为String类中的三个私有成员变量,因为这种实现还在引用原先的字符串变量value[] 通过offset(起始位置)和count(字符所占个数)返回一个新的字符串,这样可能导致jvm认为最初被截取的字符串还被引用就不对其gc,如果这个原始字符串很大,就会占用着内存,出现内存泄漏等gc问题。 jdk1.7以后的写法变化 //虽然这边还是有offse和count参数 但不是成员变量了 private final char value[]; /** Cache the hash code for the string */ private int hash; // Default to 0 ... public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > value.length) { throw new StringIndexOutOfBoundsException(endIndex); } int subLen = endIndex - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIndex, subLen);//构造函数参数顺序也有所变化 } ... public String(char value[], int offset, int count) { if (offset < 0) { throw new StringIndexOutOfBoundsException(offset); } if (count < 0) { throw new StringIndexOutOfBoundsException(count); } // Note: offset or count might be near -1>>>1. if (offset > value.length - count) { throw new StringIndexOutOfBoundsException(offset + count); } //新的不是引用之前的而是重新新建了一个。 this.value = Arrays.copyOfRange(value, offset, offset+count); } 3.hashcode public int hashCode() { int h = hash; //如果hash没有被计算过,并且字符串不为空,则进行hashCode计算 if (h == 0 && value.length > 0) { char val[] = value; //计算过程 //s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } //hash赋值 hash = h; } return h; } //String重写了Object类的hashcode方法,根据值来计算hashcode值,不过Object的该方法为native本地方法。 //该方法设计十分巧妙,它先从0判断字符大小,如果 //hashcode其实就是散列码 这种算法的话 同样的字符串的值一定相等 但不同的字符串其实也有可能得到同样的hashcode值 n=3 i=0 -> h = 31 * 0 + val[0] i=1 -> h = 31 * (31 * 0 + val[0]) + val[1] i=2 -> h = 31 * (31 * (31 * 0 + val[0]) + val[1]) + val[2] //以字符串 "123"为例 1的的ascil码为49 所以 "1".hashcode()的值为49,2为50... h = 31 * (31 * (31 * 0 + val[0]) + val[1]) + val[2] = 31 * (31 * 49 + 50) + 51 = 48690 详细算法参考这里 String的不可变性 //这边可能存在一个疑问 s对象是否发生了改变 String s = "hello"; s = "world"; //String不可变不是在原内存地址上修改数据,而是重新指向一个新对象,新地址,所以这里的hello对象并没有被改变。 //同样的类似replace方法源码中 public String replace(char oldChar, char newChar) { if (oldChar != newChar) { int len = value.length; int i = -1; char[] val = value; /* avoid getfield opcode */ while (++i < len) { if (val[i] == oldChar) { break; } } if (i < len) { char buf[] = new char[len]; for (int j = 0; j < i; j++) { buf[j] = val[j]; } while (i < len) { char c = val[i]; buf[i] = (c == oldChar) ? newChar : c; i++; } return new String(buf, true);//这边返回的是新的一个String对象 而不改变原来的对象 } } return this; //如果都一样 就指向同一个对象了 } String对象不可变 String对象为什么不可变 String用final修饰是为了防止被继承进而破坏,而让String对象不可变主要也是为了安全。 这里原来我有一个误区,仅仅认为说final修饰了String类,所以String对象不可变,想法很天真,,final修饰类的话主要是让类不可被继承,final修饰基本类型变量不能对基本类型对象重新赋值,但对于引用类型的变量(如数组),它保存的只是一个引用,final只需保证这个引用的地址不改变,即一直引用同一个对象即可,但是这个对象还是能改变的。 比如 final int[] arr = {1}; arr[0] = 3; //改变 arr = new int[]{3}; //因为这个是个新的数组 这样改变了数组的地址 编译不通过 除非去掉final //String类源码中的成员变量 (jdk1.8) /** The value is used for character storage. */ private final char value[]; /** Cache the hash code for the string */ private int hash; // Default to 0 String.png 思考 1.String对象是否真的不可变 可以通过反射改变 String的成员变量为final修饰,就是初始化之后不可改变,但是这几个成员中value比较特殊,因为他是个引用变量而不是真正的对象,value[]是final修饰的,也就是说不能再指向其他数组对象,但是可以改变数组内部的结构来改变。 注:简单来说就是final修饰数组,指定数组所指向的内存空间固定,数组内部值还能改。因为数组是引用类型,内存地址是不可改变的。 实例代码 public static void testReflection() throws Exception { String s = "Hello,World"; System.out.println("s = " + s); //Hello World //获取String类中的value字段 Field valueOfString = String.class.getDeclaredField("value"); //改变value属性的访问权限 valueOfString.setAccessible(true); //获取s对象上的value属性的值 char[] value = (char[]) valueOfString.get(s); //改变value所引用的数组中的第5个字符 value[5] = '_'; System.out.println("s = " + s); //Hello_World } String为什么要设计成不可变 1.允许String对象缓存hashcode: Java中String对象的哈希码被频繁地使用, 比如在hashMap 等容器中。字符串不变性保证了hash码的唯一性,因此可以放心地进行缓存。 2.安全性 String被许多的Java类(库)用来当做参数,例如 网络连接地址URL,文件路径path,还有反射机制所需要的String参数等, 假若String不是固定不变的,将会引起各种安全隐患。 对于一个方法而言,参数是为该方法提供信息的,而不是让方法改变自己。 3.字符串常量池的需要 字符串常量池(String pool, String intern pool, String保留池) java堆内存放了一个特殊的区域用于常量池, 当创建一个String对象时,假如此字符串值已经存在于常量池中,则不会创建一个新的对象,而是引用已经存在的对象。

优秀的个人博客,低调大师

Java并发编程实战系列5之基础构建模块

1 同步容器类 同步容器类包括Vector和HashTable,二者是早期JDK一部分,此外还包括在JDK 1.2中添加的一些功能相似的类,这些的同步封装器类是由Collections.synchronizedXxx等工厂方法创建的。这些类实现线程安全的方式是:将他们的状态封装起来,并对每个共有方法进行同步,使得每次只有一个线程能访问容器的状态。 1.1 同步容器类的问题 同步容器类都是线程安全的,但在某些情况可能需额外客户端加锁来保护复合操作。 容器上常见的复合操作包括: 迭代(反复访问元素,直到遍历完容器中所有元素) 跳转(根据指定顺序找到当前元素的下一个元素)以及条件运算 在同步容器类中,这些复合操作在没有客户端加锁的情况下,仍是线程安全的, 但当其他线程并发的修改容器时,他们可能会表现出意料之外的行为。 2 并发容器 Java5提供了多种并发容器来改进同步容器的性能。 同步容器将所有对容器状态的访问都串行化,以实现他们的线程安全性。 这种方法的代价是严重降低并发性,当多个线程竞争容器的锁时,吞吐量将严重降低。 并发容器是针对多个线程并发访问设计的。在Java 5中增加了 ConcurrentHashMap,用来替代同步且基于散列的Map,增加了对一些常见符合操作的支持,例如“若没有则添加”、替换以及有条件删除等。 CopyOnWriteArrayList,用于在遍历操作为主要操作的情况下代替同步的List。 copyOnWriteArrayList 和 copyOnWriteSet 一开始都共享同一个内容,当想要修改内容时,才会真正的把内容 copy 出去,形成一个新的内容后再改 比如:当我们往一个容器添加元素时,不直接往当前容器添加,而是先将容器进行 copy,复制出一个新容器,再往新容器里加元素。添加完之后,再将原容器引用指向新容器。 好处:对 copyOnWrite 容器进行并发读时,不需要加锁,因为当前容器不会增加新元素,读写分离 copyOnWriteArrayList#add要加锁,否则多线程时会 copy N 个副本 copyOnWrite 适合于 读多写少场景,但只能保证数据最终一致性,不保证实时一致性 若你希望写入马上被读到,不要用 copyOnWrite 容器 通过并发容器来代替同步容器,可以极大地提供伸缩性并降低风险。 2.1 CocurrentHashMap 同步容器在执行每个操作期间都持有一个锁。在一些操作中,例如HashMashMap.get或List.contains,可能包含大量的工作:当遍历散列桶或链表来查找某个特定的对象时,必须在许多元素上调用equals。在基于散列的容器中,如果hashCode不能很均匀的分布散列值,那么容器中的元素就不会均匀的分布在整个容器中。某些情况下,某个糟糕的散列函数还会把一个散列表变成线性链表。当遍历很长的链表并且在某些或者全部元素上调用equals方法时,会花费很长时间,而其他线程在这段时间内都不能访问容器。 ConcurrentHashMap使用一种粒度更细的称为分段锁的机制来实现更大程度的共享. 在这种机制中,任意数量的读取线程可以并发的访问Map,执行读操作的线程和执行写操作的线程可以并发的访问Map,并且一定数量的写线程可以并发的修改Map. ConcurrentHashMap与其他并发容器一起增强了同步容器:迭代器不会抛出ConcurrentModificationException,因此迭代过程无需加锁. 其迭代器具有"弱一致性",而并非"及时失败".可以容忍并发的修改,当创建迭代器时会遍历已有的元素,并可以(但不保证)在迭代器被构造后将修改操作反映给容器. 只有当需要加锁Map以进行独占访问时,才应该放弃使用ConcurrentHashMap. 2.2 额外的原子Map操作 由于ConcurrentHashMap不能被加锁来执行独占访问,因此 无法使用客户端加锁来创建新的原子操作. 一些常见的复合操作,eg."若没有则添加","若相等则移除"等,都已经实现为原子操作并且在ConcurrentMap接口中声明,如下面代码所示. public interface ConcurrentMap<K, V> extends Map<K, V> { //仅当K没有相应的映射值时才插入 V putIfAbsent(K key, V value); //仅当K被映射到V时才移除 boolean remove(Object key, Object value); //仅当K被映射到oldValue时才替换为newValue boolean replace(K key, V oldValue, V newValue); //仅当K被映射到某个值时才被替换为newValue V replace(K key, V value); }

优秀的个人博客,低调大师

JavaScript进阶【三】JavaScript面向对象的基础知识复习

版权声明:本文为博主原创文章,未经博主允许不得转载。更多学习资料请访问我爱科技论坛:www.52tech.tech https://blog.csdn.net/m0_37981569/article/details/79547464 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JavaScript面向对象知识复习</title> </head> <body> <h2></h2> <script type="text/javascript"> /************************************************类,成员属性,成员方法******************************************************/ /** * 定义一个类 * @param name * @param age * @constructor */ function MyClass(name, age) { this.name = name; this.age = age; // 成员方法 this.toString = function () { alert(cls1.name+":"+cls1.age); }; }; /** * 实例化一个cls1对象 * @type {MyClass} */ var cls1 = new MyClass("xiugang", 15); //alert(cls1.name+":"+cls1.age); cls1.toString(); // 再给这个类的一个对象cls2添加一个方法 var cls2 = new MyClass("zhangsan", 25); cls2.ShowName = function () { alert(this.name+":"+this.age); }; cls2.ShowName(); // 使用Prototype对象来给函数添加方法 function Animal(name, age) { this.name = name; this.age = age; } Animal.prototype.toString = function () { alert(this.name+":"+this.age); }; // 实例化两个对象 var dog = new Animal("dog", 15); dog.toString(); var cat = new Animal("cat", 16); cat.toString(); // 利用prototype属性给一个类添加多个方法 function Person(name, age) { this.name = name; this.age = age; }; Person.prototype = { toString : function () { alert(this.name+":"+this.age); }, sayHello : function () { alert("say Hello!"); } }; var student = new Person("小明", 25); student.sayHello(); student.toString(); /************************************************静态类******************************************************/ var StaticClass = function () { } StaticClass.name = "StaticClass"; StaticClass.Sum = function (value1, value2) { return value1 + value2; }; alert(StaticClass.name+", "+StaticClass.Sum(10, 20)); /************************************************继承******************************************************/ function PeopleClass() { this.type = "People"; }; PeopleClass.prototype = { getType : function () { alert("This is a Person"); } }; function StudentClass(name, sex) { // 使用apply方法将父类对象的构造函数绑定到子类对象上 PeopleClass.apply(this, arguments); this.name = name; this.sex = sex; } var stu = new StudentClass("小红", "女"); alert(stu.type); // 实现了属性的继承 /** * 实现方法的继承 */ function Sophermore(name, sex) { PeopleClass.apply(this, arguments); // 实现父类方法的继承 /** * 实现思路: 需要循环将父类对象的prototype进行赋值, 即可达到继承的目的 */ var prop; for (prop in PeopleClass.prototype){ var proto = this.constructor.prototype; if (!proto[prop]){ proto[prop] = PeopleClass.prototype[prop]; } proto[prop]["super"] = PeopleClass.prototype; } this.name = name; this.sex = sex; } var stu2 = new Sophermore("xiuxiu", 22); alert(stu2.type); stu2.getType() /** * 方法二:实现继承的第二种方法, 使用对象冒充的方法 */ function AnimalNew(name, age) { this.name = name; this.age = age; this.Sum = function () { alert(this.name+","+this.age); } } // 成员方法 /*AnimalNew.prototype = { sayhello : function () { alert(this.name+"is saying Hello!"); }, sayAge : function () { alert(this.name+"'s age is "+this.age); } }*/ AnimalNew.prototype.sayHello = function () { alert(this.name+" is saying Haha!"); } // 子类开始实现继承 function Duck(name, age) { this.animal = AnimalNew; this.animal(name, age); } var duck = new Duck("鸭子", 12); //duck.sayHello(); //error! //duck.sayAge(); //error! //duck.sayHello(); //error! duck.Sum(); //ok的! /************************************************JavaScript继承知识加强******************************************************/ function Animal(name) { // 属性 this.name = name; //实例方法 this.sleep = function () { console.log(this.name+"正在睡觉!"); } } // 原型方法 Animal.prototype.eat = function (food) { console.log(this.name+"正在吃"+food); } /** * 方法一: 将父类的实例作为子类的原型, 可以同时实现父类的属性和方法的继承 */ function Cat() { } Cat.prototype = new Animal(); Cat.prototype.name = "cat"; // test var cat =new Cat(); console.log(cat.name); cat.sleep() cat.eat("fish"); console.log(cat instanceof Animal); console.log(cat instanceof Cat); /** * 方法二: 组合继承 * 通过调用父类构造,继承父类的属性并保留传参的优点,然后通过将父类实例作为子类原型,实现函数复用 */ function Cow(name) { Animal.call(this); this.name = name; } Cow.prototype = new Animal(); Cow.prototype.constructor = Cat; var cow = new Cow("小牛博客"); console.log(cow.name); console.log(cow.sleep()); console.log(cat instanceof Animal); console.log(cat instanceof Cat); // 利用方法二:组合继承实现继承的综合案例 function Family(name, age) { // 属性 this.name = name; this.age = age; // 实例方法 this.Member = function () { alert("This family is having 5 memnbers now!"); } }; // 原型方法 Family.prototype = { sayHello : function () { alert(this.name +" is saying hello!"); }, sayAge : function () { alert(this.name +" is saying age:"+this.age); } }; // 开始实现继承 function Son(name, age) { Family.call(this); this.name = name; this.age = age; } Son.prototype = new Family(); Son.prototype.constructor = Family; // 开始测试 var son = new Son("王老大", 15); alert(son.age+", "+son.age); son.sayAge(); son.sayHello(); alert(son instanceof Family); alert(son instanceof Son); </script> </body> </html>

优秀的个人博客,低调大师

01.Java基础(多线程回顾,对比Linux多线程)

两个线程间通信,实现交替打印 public class Thread1 { public static void main(String[] args) { final Printer printer = new Printer(); new Thread(new Runnable() { @Override public void run() { while(true){ try { printer.print1(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { while(true){ try { printer.print2(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); } } /** * 等待唤醒机制,两个线程间通信 * @author renzhenming * */ class Printer{ private int flag = 1; public void print1() throws InterruptedException{ synchronized(this){ if (flag !=1) { /** * obj.wait():该方法的调用,使得调用该方法的执行线程(T1)放弃obj的对象锁并阻塞, * 直到别的线程调用了obj的notifyAll方法、或者别的线程调用了obj的notify方法且JVM选择唤醒(T1), * 被唤醒的线程(T1)依旧阻塞在wait方法中,与其它的线程一起争夺obj的对象锁, * 直到它再次获得了obj的对象锁之后,才能从wait方法中返回。 * (除了notify方法,wait还有带有时间参数的版本,在等待了超过所设时间之后, * T1线程一样会被唤醒,进入到争夺obj对象锁的行列;另外中断可以直接跳出wait方法) * * 1.在同步代码块中,用哪个对象锁就用哪个对象调用wait方法, * 2.为什么wait和notify这些方法要定义在Object类中?因为锁对象可以是任意对象,那么任意对象的类都是Object的子类,Object是任意类的基类,所以将方法定义在Object这个类中就会让任意对象对其进行调用 * sleep和wait方法的区别:a.sleep在同步代码块或同步函数中,不释放锁,(睡着了也会抱着锁睡),wait相反会释放锁 b.sleep方法必须传入参数,参数就是时间,时间到了自动醒来,wait方法可以传入时间参数,也可以不传入时间参数,如果给wait方法传入时间参数,用法与sleep相似,时间到了就停止等待(通常都是用没有参数的wait方法) */ this.wait(); } System.out.print("y"); System.out.print("i"); System.out.print("n"); System.out.print("g"); System.out.print("z"); System.out.print("i"); System.out.print("\r\n"); flag = 2; /** * obj.notify():该方法的调用,会从所有正在等待obj对象锁的线程中,唤醒其中的一个(选择算法依赖于不同实现), * 被唤醒的线程此时加入到了obj对象锁的争夺之中,然而该notify方法的执行线程此时并未释放obj的对象锁, * 而是离开synchronized代码块时释放。因此在notify方法之后,synchronized代码块结束之前, * 所有其他被唤醒的,等待obj对象锁的线程依旧被阻塞。 */ this.notify(); } } public void print2() throws InterruptedException{ synchronized (this) { if (flag != 2) { wait(); } System.out.print("z"); System.out.print("h"); System.out.print("e"); System.out.print("n"); System.out.print("m"); System.out.print("i"); System.out.print("n"); System.out.print("g"); System.out.print("\r\n"); flag = 1; notify(); } } } 打印结果 yingzi zhenming yingzi zhenming yingzi zhenming yingzi zhenming yingzi zhenming yingzi zhenming yingzi zhenming yingzi zhenming yingzi zhenming ... 三个线程或三个以上通信(试错,期待的结果是逐条打印,实际结果看下边) 按照上边的方式,代码如下: public class Thread1 { public static void main(String[] args) { final Printer printer = new Printer(); new Thread(new Runnable() { @Override public void run() { while(true){ try { printer.print1(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { while(true){ try { printer.print2(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { while(true){ try { printer.print3(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); } } /** * 等待唤醒机制,两个线程间通信 * @author renzhenming * */ class Printer{ private int flag = 1; public void print1() throws InterruptedException{ synchronized(this){ if (flag !=1) { /** * obj.wait():该方法的调用,使得调用该方法的执行线程(T1)放弃obj的对象锁并阻塞, * 直到别的线程调用了obj的notifyAll方法、或者别的线程调用了obj的notify方法且JVM选择唤醒(T1), * 被唤醒的线程(T1)依旧阻塞在wait方法中,与其它的线程一起争夺obj的对象锁, * 直到它再次获得了obj的对象锁之后,才能从wait方法中返回。 * (除了notify方法,wait还有带有时间参数的版本,在等待了超过所设时间之后, * T1线程一样会被唤醒,进入到争夺obj对象锁的行列;另外中断可以直接跳出wait方法) */ this.wait(); } System.out.print("y"); System.out.print("i"); System.out.print("n"); System.out.print("g"); System.out.print("z"); System.out.print("i"); System.out.print("\r\n"); flag = 2; /** * obj.notify():该方法的调用,会从所有正在等待obj对象锁的线程中,唤醒其中的一个(选择算法依赖于不同实现), * 被唤醒的线程此时加入到了obj对象锁的争夺之中,然而该notify方法的执行线程此时并未释放obj的对象锁, * 而是离开synchronized代码块时释放。因此在notify方法之后,synchronized代码块结束之前, * 所有其他被唤醒的,等待obj对象锁的线程依旧被阻塞。 */ this.notify(); } } public void print2() throws InterruptedException{ synchronized (this) { if (flag != 2) { wait(); } System.out.print("z"); System.out.print("h"); System.out.print("e"); System.out.print("n"); System.out.print("m"); System.out.print("i"); System.out.print("n"); System.out.print("g"); System.out.print("\r\n"); flag = 3; notify(); } } public void print3() throws InterruptedException{ synchronized (this) { if (flag != 3) { wait(); } System.out.print("f"); System.out.print("a"); System.out.print("l"); System.out.print("l"); System.out.print("i"); System.out.print("n"); System.out.print("l"); System.out.print("o"); System.out.print("v"); System.out.print("e"); System.out.print("\r\n"); flag = 1; notify(); } } } 结果: zhenming yingzi zhenming yingzi zhenming yingzi zhenming yingzi zhenming yingzi zhenming yingzi zhenming fallinlove zhenming ... 为什么会出现上边的情况?我们极端分析一下,假设,第一个回合中,首先执行的是第2和第3个线程,也就是print2 print3方法,此时,由于flag不满足执行条件,两个线程都进入了等待状态,然后执行print1打印了一条,设置flag=2,然后notify,此时通常疏忽的开发人员可能会想当然的认为,flag=2 了,那么理所当然应该唤醒线程2了,应该打印print2了,事实上并非如此,由于notify是随机唤醒一个线程,那么它可能唤醒2 也可能唤醒3,假设此时被唤醒的线程是3,由于if语句的特性,不会重新判断执行条件,而是在哪里等待,在哪里醒来,于是直接跳过了判断语句执行了print3的打印内容,所以就出现了这种情况 针对这种问题,我们尝试用while代替if做条件判断,while是循环判断,每次判断都会判断标记,我们对程序做修改后如下: public class Thread1 { public static void main(String[] args) { final Printer printer = new Printer(); new Thread(new Runnable() { @Override public void run() { while(true){ try { printer.print1(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { while(true){ try { printer.print2(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { while(true){ try { printer.print3(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); } } /** * 等待唤醒机制,两个线程间通信 * @author renzhenming * */ class Printer{ private int flag = 1; public void print1() throws InterruptedException{ synchronized(this){ while (flag !=1) { /** * obj.wait():该方法的调用,使得调用该方法的执行线程(T1)放弃obj的对象锁并阻塞, * 直到别的线程调用了obj的notifyAll方法、或者别的线程调用了obj的notify方法且JVM选择唤醒(T1), * 被唤醒的线程(T1)依旧阻塞在wait方法中,与其它的线程一起争夺obj的对象锁, * 直到它再次获得了obj的对象锁之后,才能从wait方法中返回。 * (除了notify方法,wait还有带有时间参数的版本,在等待了超过所设时间之后, * T1线程一样会被唤醒,进入到争夺obj对象锁的行列;另外中断可以直接跳出wait方法) */ this.wait(); } System.out.print("y"); System.out.print("i"); System.out.print("n"); System.out.print("g"); System.out.print("z"); System.out.print("i"); System.out.print("\r\n"); flag = 2; /** * obj.notify():该方法的调用,会从所有正在等待obj对象锁的线程中,唤醒其中的一个(选择算法依赖于不同实现), * 被唤醒的线程此时加入到了obj对象锁的争夺之中,然而该notify方法的执行线程此时并未释放obj的对象锁, * 而是离开synchronized代码块时释放。因此在notify方法之后,synchronized代码块结束之前, * 所有其他被唤醒的,等待obj对象锁的线程依旧被阻塞。 */ this.notify(); } } public void print2() throws InterruptedException{ synchronized (this) { while (flag != 2) { wait(); } System.out.print("z"); System.out.print("h"); System.out.print("e"); System.out.print("n"); System.out.print("m"); System.out.print("i"); System.out.print("n"); System.out.print("g"); System.out.print("\r\n"); flag = 3; notify(); } } public void print3() throws InterruptedException{ synchronized (this) { while (flag != 3) { wait(); } System.out.print("f"); System.out.print("a"); System.out.print("l"); System.out.print("l"); System.out.print("i"); System.out.print("n"); System.out.print("l"); System.out.print("o"); System.out.print("v"); System.out.print("e"); System.out.print("\r\n"); flag = 1; notify(); } } } 更离谱的问题出现,打印结果: yingzi zhenming fallinlove 三个线程在执行一次之后就全部停了,或者说全部进入了等待状态,为什么会出现这一现象? 假设程序执行开始,先执行了线程2线程3,由于flag条件不满足,两个线程都进入等待状态,此时线程1开始执行,设置flag=2,执行完毕notify唤醒一个线程,并且由于自身条件也陷入等待状态,假设先唤醒的是线程3,由于flag值不对,线程3仍然处于等待状态,这种情况下,三个线程全部陷入等待状态 notify随机唤醒一个线程,是导致这一问题出现的原因,那么可否唤醒全部线程呢, notifyall就出现了,notifyAll可以唤醒全部线程,然后根据条件的判断执行相应的线程,但是这样做是由弊端的,那就是每次都要将所有线程唤醒,这是JDK1.5之前的处理办法,JDK1.5有新的方法解决这一问题 public class Thread1 { public static void main(String[] args) { final Printer printer = new Printer(); new Thread(new Runnable() { @Override public void run() { while(true){ try { printer.print1(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { while(true){ try { printer.print2(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { while(true){ try { printer.print3(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); } } /** * 等待唤醒机制,两个线程间通信 * @author renzhenming * */ class Printer{ private int flag = 1; public void print1() throws InterruptedException{ synchronized(this){ while (flag !=1) { /** * obj.wait():该方法的调用,使得调用该方法的执行线程(T1)放弃obj的对象锁并阻塞, * 直到别的线程调用了obj的notifyAll方法、或者别的线程调用了obj的notify方法且JVM选择唤醒(T1), * 被唤醒的线程(T1)依旧阻塞在wait方法中,与其它的线程一起争夺obj的对象锁, * 直到它再次获得了obj的对象锁之后,才能从wait方法中返回。 * (除了notify方法,wait还有带有时间参数的版本,在等待了超过所设时间之后, * T1线程一样会被唤醒,进入到争夺obj对象锁的行列;另外中断可以直接跳出wait方法) */ this.wait(); } System.out.print("y"); System.out.print("i"); System.out.print("n"); System.out.print("g"); System.out.print("z"); System.out.print("i"); System.out.print("\r\n"); flag = 2; /** * obj.notify():该方法的调用,会从所有正在等待obj对象锁的线程中,唤醒其中的一个(选择算法依赖于不同实现), * 被唤醒的线程此时加入到了obj对象锁的争夺之中,然而该notify方法的执行线程此时并未释放obj的对象锁, * 而是离开synchronized代码块时释放。因此在notify方法之后,synchronized代码块结束之前, * 所有其他被唤醒的,等待obj对象锁的线程依旧被阻塞。 */ this.notifyAll(); } } public void print2() throws InterruptedException{ synchronized (this) { while (flag != 2) { wait(); } System.out.print("z"); System.out.print("h"); System.out.print("e"); System.out.print("n"); System.out.print("m"); System.out.print("i"); System.out.print("n"); System.out.print("g"); System.out.print("\r\n"); flag = 3; notifyAll(); } } public void print3() throws InterruptedException{ synchronized (this) { while (flag != 3) { wait(); } System.out.print("f"); System.out.print("a"); System.out.print("l"); System.out.print("l"); System.out.print("i"); System.out.print("n"); System.out.print("l"); System.out.print("o"); System.out.print("v"); System.out.print("e"); System.out.print("\r\n"); flag = 1; notifyAll(); } } } 结果: yingzi zhenming fallinlove yingzi zhenming fallinlove yingzi zhenming fallinlove yingzi zhenming fallinlove yingzi zhenming fallinlove ... JDK1.5互斥锁 所谓互斥锁, 指的是一次最多只能有一个线程持有的锁. 在jdk1.5之前, 我们通常使用synchronized机制控制多个线程对共享资源的访问. 而现在, Lock提供了比synchronized机制更广泛的锁定操作, Lock和synchronized机制的主要区别: synchronized机制提供了对与每个对象相关的隐式监视器锁的访问, 并强制所有锁获取和释放均要出现在一个块结构中, 当获取了多个锁时, 它们必须以相反的顺序释放. synchronized机制对锁的释放是隐式的, 只要线程运行的代码超出了synchronized语句块范围, 锁就会被释放. 而Lock机制必须显式的调用Lock对象的unlock()方法才能释放锁, 这为获取锁和释放锁不出现在同一个块结构中, 以及以更自由的顺序释放锁提供了可能。 import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class Thread1 { public static void main(String[] args) { final Printer printer = new Printer(); new Thread(new Runnable() { @Override public void run() { while (true) { try { printer.print1(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true) { try { printer.print2(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true) { try { printer.print3(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); } } /** * 等待唤醒机制,互斥锁 * * @author renzhenming * */ class Printer { ReentrantLock r = new ReentrantLock(); Condition c1 = r.newCondition(); Condition c2 = r.newCondition(); Condition c3 = r.newCondition(); private int flag = 1; public void print1() throws InterruptedException { r.lock(); if (flag != 1) { c1.await(); } System.out.print("y"); System.out.print("i"); System.out.print("n"); System.out.print("g"); System.out.print("z"); System.out.print("i"); System.out.print("\r\n"); flag = 2; c2.signal(); r.unlock(); } public void print2() throws InterruptedException { r.lock(); if (flag != 2) { c2.await(); } System.out.print("z"); System.out.print("h"); System.out.print("e"); System.out.print("n"); System.out.print("m"); System.out.print("i"); System.out.print("n"); System.out.print("g"); System.out.print("\r\n"); flag = 3; c3.signal(); r.unlock(); } public void print3() throws InterruptedException { r.lock(); if (flag != 3) { c3.await(); } System.out.print("f"); System.out.print("a"); System.out.print("l"); System.out.print("l"); System.out.print("i"); System.out.print("n"); System.out.print("l"); System.out.print("o"); System.out.print("v"); System.out.print("e"); System.out.print("\r\n"); flag = 1; c1.signal(); r.unlock(); } } 结果,按照唤醒顺序执行线程,不再需要使用while判断,if即可 fallinlove yingzi zhenming fallinlove yingzi zhenming fallinlove yingzi zhenming fallinlove yingzi zhenming fallinlove yingzi zhenming fallinlove yingzi zhenming fallinlove yingzi zhenming ...

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码