代码改变世界

android开发 线程同步锁

2016-03-17 17:46  宁小哥  阅读(861)  评论(0)    收藏  举报

package test;

public class MyThread implements Runnable{

    public void run() {
        
        
            
            for(int i = 5000 ; i > 0 ; i--){
                synchronized (this) {
                    System.out.println(Thread.currentThread().getName() + i);
                
                    Thread.yield();
                    }
            }
        
    }
}

 

package test;

public class Test {
    public static void main(String args []) {
        
        MyThread myThread = new MyThread();
        
        Thread thread1 = new Thread(myThread);
        Thread thread2 = new Thread(myThread);
        
        thread1.setName("线程1 ");
        thread2.setName("线程2 ");
        
        thread1.start();
        thread2.start();
        
    }
}    

补充:还用同步方法 和上面用法相似 只是把synchronized关键字写在了方法名前面 比如:

public  synchronized void run(){

  //code

}