多线程入门--synchronized介绍
来源:互联网 发布:旧时光影视论坛新域名 编辑:程序博客网 时间:2024/05/06 07:22
线程安全
非线程安全主要是指多个线程对同一个对象中 的同一个实例变量进行操作时会出现值被更改、值不同步的情况,进而影响程序的执行流 程。
/**
* 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: 2C is running!B is running!C count: 0E is running!D is running!E count: 0B count: 0D 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!"); }
0 0
- 多线程入门--synchronized介绍
- java 多线程 synchronized 入门博文二
- java 多线程 Synchronized的简单介绍
- Java多线程入门:Synchronized同步类方法
- 多线程编程入门介绍
- synchronized多线程
- 多线程-synchronized
- Java多线程技术入门介绍
- java多线程基础---synchronized与ReentrantReadWriteLock的介绍和比较
- synchronized 介绍
- JAVA并发入门与多线程介绍
- synchronized多线程同步
- java Synchronized 多线程同步
- Java多线程Synchronized心得
- Java多线程之synchronized
- Java多线程之synchronized
- 多线程runnable 和 synchronized
- 【多线程】synchronized同步块
- CocoaPods报错:The dependency `AFNetworking (~> 3.0.4s)` is not used in any concrete target
- gcc编译参数-fPIC的一些问题
- UOJ30——【CF Round #278】Tourists
- Xcode 在创建工程时,文件名默认有一个自己专有的前缀
- Android中MediaButtonReceiver广播监听器的机制分析
- 多线程入门--synchronized介绍
- java.lang.OutOfMemoryError:GC overhead limit exceeded填坑心得
- java多态
- sprintf
- 工程云存储软件
- 使用Ionic + Apache Cordova开发跨平台混合型的移动应用
- Maven 运行命令
- Wireshark 基本介绍和学习 TCP 三次握手
- jquery禁用a标签,jquery禁用按钮click点击