1.个人理解
就是两个或者多个线程同时共享一个资源的时候,对资源进行改动这类操作时,就会存在竞态条件。改动的那个方法就是竞态条件中的临界区。
2.示例
public class CompetiveCondition {
//多线程中要知道他们共享的是什么,这里共享的是NotThreadSafe对象
public static void main(String[] args) {
//公用实例
NotThreadSafe instance = new NotThreadSafe();
//主线程一
MyRunnable myRunnable = new MyRunnable(instance);
Thread thread = new Thread(myRunnable);
thread.start();
//主线程二
new Thread(new MyRunnable(instance)).start();
//主线程三
new Thread(new MyRunnable(instance)).start();
}
}
class NotThreadSafe{
StringBuilder builder = new StringBuilder();
//竞态条件中的临界区
public void add(String text) { //synchronized
this.builder.append(text);
System.out.println(builder.toString());
}
}
class MyRunnable implements Runnable {
NotThreadSafe instance = null;
MyRunnable(NotThreadSafe instance){
this.instance = instance;
}
public void run() {
this.instance.add(" some text");
}
}
//上面起的两个线程中传入的是同一个方法主体实例,所以会产生竞态条件的. 方法就是临界区
//线程控制逃逸规则: 如果一个资源的创建,使用销毁都在同一个线程内完成,且永远不会脱离该线程的控制,则该资源的使用就是安全的。
网友评论