---
title: "线程的同步"
author: "youyang_java"
date: "2014-04-21T16:03:48Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2014-04-21T16:03:48Z"
id: 2051354
url: "https://youyang-java.iteye.com/blog/2051354"
---

![](http://dl2.iteye.com/upload/attachment/0096/3359/85c9f852-b3d4-3298-ab7e-4870b0f0c44d.png)  
 

public class TraditionalSychronized {  
     
    /\**  
     * @param args  
     \*/  
    public static void main(String\[] args) {  
        new TraditionalSychronized().init();  
         
    }  
     
    public void init() {  
         
        final Printer printer = new Printer();  
         
        new Thread() {  
             
            @Override  
            public void run() {  
                 
                while (true) {  
                     
                    try {  
                        Thread.sleep(10);  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                    printer.print("youyang");  
                }  
                 
            }  
             
        }.start();  
         
        new Thread() {  
             
            @Override  
            public void run() {  
                 
                while (true) {  
                     
                    try {  
                        Thread.sleep(10);  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                    printer.print("yusiyi");  
                }  
            }  
             
        }.start();  
    }  
     
    static class Printer {  
        public void print(String string) {  
            //当线程运行到这里时，就会检查this的锁是否还在，在就获取锁，运行里面的代码  
            //如果锁不在，就等待，直到得到锁  
            synchronized (this) {  
                for (int i = 0; i &lt; string.length(); i++) {  
                    System.out.print(string.charAt(i));  
                }  
                System.out.println();  
            }  
        }  
         
        //synchronized方法中用到的互斥对象也是this，所以print方法和print2方法能同步  
        public synchronized void print2(String string) {  
            for (int i = 0; i &lt; string.length(); i++) {  
                System.out.print(string.charAt(i));  
            }  
            System.out.println();  
        }  
         
        //static synchronized方法中用到的互斥对象就是类本身，即Printer.class,所以不能和print方法同步  
        public static synchronized void print3(String string) {  
            for (int i = 0; i &lt; string.length(); i++) {  
                System.out.print(string.charAt(i));  
            }  
            System.out.println();  
        }  
    }  
     
}