多线程问题——源码分析讲解


一个线程执行互斥代码的过程        
1. 获得同步锁;
        2. 清空工作内存;
        3. 从主内存拷贝对象副本到工作内存;
        4. 执行代码(计算或者输出等);
        5. 刷新主内存数据;
        6. 释放同步锁。
标签: <无>代码片段(2)[全屏查看所有代码]

1. [代码]线程不同步     
package boom;
public class test { 
    public static void main(String[] args) { 
        final Outputter output = new Outputter(); 
        new Thread() { 
            public void run() { 
                try {
                    output.output("zhangsan");
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } 
            } 
        }.start();       
        new Thread() { 
            public void run() { 
                try {
                    output.output("lisi");
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } 
        }.start(); 
    } 

class Outputter { 
    public void output(String name) throws InterruptedException { 
        // TODO 为了保证对name的输出不是一个原子操作,这里逐个输出name的每个字符 
        for(int i = 0; i < name.length(); i++) { 
            System.out.print(name.charAt(i)); 
            Thread.sleep(1000);
            // Thread.sleep(10); 
        } 
    } 
}
 
//输出zlhiasnigsan

2. [代码]添加同步锁     ?
class Outputter { 
    public synchronized void output(String name) throws InterruptedException { 
        // TODO 为了保证对name的输出不是一个原子操作,这里逐个输出name的每个字符 
        for(int i = 0; i < name.length(); i++) { 
            System.out.print(name.charAt(i)); 
            Thread.sleep(1000);
            // Thread.sleep(10); 
        } 
    } 
}
宣传图片1.jpg

0 个评论

要回复文章请先登录注册

Template error, template file not found