synchronized run()方法
来源:互联网 发布:云计算技术 2016 编辑:程序博客网 时间:2024/06/07 03:52
最近编程有一个需求,需要某个线程只能有一个run()方法在执行,然后自然而然想到了用synchronized修饰run()方法来解决这个问题,详细代码如下:
- public class VolatileThread extends Thread {
- public synchronized void run() {
- for (int i = 0; i < 10; i++) {
- System.out.println(Thread.currentThread().getName());
- }
- }
- public static void main(String[] args) {
- for (int i = 0; i < 3; i++) {
- VolatileThread vt = new VolatileThread();
- //设置线程的名称,看在执行哪个对象的run()
- vt.setName(i + "");
- vt.start();
- }
- }
- }
但是最终的执行结果还是同时会有多个线程在执行run()中的代码,然后百思不得其解,想了很久,才发现问题所在。在方法上加synchronized等同于synchronized(this),虽然看似给run()方法加上了锁,但是我们看main()中是如何去产生多个线程的,是分别new出了三个不同的线程对象。也就是说三个线程都拿到各自对象的锁,因此都能够执行run()中的代码。要解决这个问题其中一个方法是通过runnable接口来实现线程,详细代码如下:
- public class VolatileThread implements Runnable {
- public synchronized void run() {
- for (int i = 0; i < 10; i++) {
- System.out.println(Thread.currentThread().getName());
- }
- }
- public static void main(String[] args) {
- VolatileThread vt = new VolatileThread();
- for (int i = 0; i < 3; i++) {
- Thread td = new Thread(vt);
- //设置线程的名称,看在执行哪个对象的run()
- td.setName(i + "");
- td.start();
- }
- }
- }
0 0
- synchronized run()方法
- synchronized run()方法
- synchronized run()方法
- synchronized run()方法
- synchronized run()方法的问题
- java synchronized修饰普通方法,修饰静态方法,修饰代码块,修饰线程run方法 比较
- day11多线程,run方法。卖票多线程示例。synchronized,同步锁对象,回顾单例。死锁问题
- synchronized方法
- synchronized 方法
- synchronized()方法
- synchronized 方法
- synchronized方法
- synchronized方法和synchronized块
- synchronized 方法 synchronized关键字详解
- java synchronized详解--synchronized方法
- WshShell.Run方法说明
- Application.Run 方法
- vbs的Run方法
- ZooKeeper系列之二:Zookeeper常用命令
- unix shell 命令 使用笔记
- gdb 里设置临时变量
- android R文件丢失解决办法
- ios SDWebImage添加头部参数
- synchronized run()方法
- php 面向对象
- NOR型闪存与NAND型闪存的区别
- wpa_cli取命令函数
- iOS中设置导航栏标题的字体颜色和大小
- DataUtility 入门教程一[下拉列表:Combobox]
- 【UE】总结自己常用的UltraEdit使用技巧
- 树形视图和列表视图中的HitTest
- Oracle 12c RAC 集群使用DNS 实现 SCAN