多线程入门--synchronized介绍
2016-05-18 11:03
363 查看
线程安全
非线程安全主要是指多个线程对同一个对象中 的同一个实例变量进行操作时会出现值被更改、值不同步的情况,进而影响程序的执行流 程。/** * Allocates a new {@code Thread} object. This constructor has the same * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} * {@code (null, target, name)}. * * @param target * the object whose {@code run} method is invoked when this thread * is started. If {@code null}, this thread's run method is invoked. * * @param name * the name of the new thread */ public Thread(Runnable target, String name) { init(null, target, name, 0); }
实现多线程的资源共享:
public class Test { public static void main(String[] args) { Thread1 thread1 = new Thread1(); Thread a = new Thread(thread1, "A"); Thread b = new Thread(thread1, "B"); Thread c = new Thread(thread1, "C"); Thread d = new Thread(thread1, "D"); Thread e = new Thread(thread1, "E"); a.start(); b.start(); c.start(); d.start(); e.start(); } }
线程定义:
public class Thread1 extends Thread { private int count=5; @Override public void run() { super.run(); count--; System.out.println(Thread.currentThread().getName() + " is running!"); System.out.println(Thread.currentThread().getName() + " count: " + count); } }
虽然共享了资源,但是对资源count的访问是不同步的。
A is running! A count: 2 C is running! B is running! C count: 0 E is running! D is running! E count: 0 B count: 0 D count: 0
解决资源同步问题的一个方法是在更改资源的操作的方法前加上synchronized修饰符,表示对该方法的调用必须进行锁的争抢,只有一个线程能够进行方法的调用。
@Override synchronized public void run() { super.run(); count--; System.out.println(Thread.currentThread().getName() + " count: " + count); System.out.println(Thread.currentThread().getName() + " is running!"); }
相关文章推荐
- 学习进度12
- 中文转拼音jquery插件
- CocoaPods报错:The dependency `AFNetworking (~> 3.0.4s)` is not used in any concrete target
- 版本号问题
- 跳转Acitity时,同时finish掉多个Activity
- eclipse 创建maven web项目
- MVC HtmlHelper用法大全
- stm32使用stlink v2.0下载的sw接线方式
- leetcode 22. Generate Parentheses
- Java面试 String相关的面试点
- 五种典型的递推关系——一步一步算法篇
- Advapi32.dll 函数接口说明
- 进击的Android注入术《二》
- 在iOS上实现一个简单的日历控件
- 单例模式
- java程序员招聘现场
- (转载)数据库效率提高的方案
- linux 常见问题&解决方案
- 下载gcm.zip
- 99. Recover Binary Search Tree