【java】线程同步关键字volatile,synchronize,取消串行化关键字transient

来源:互联网 发布:莎士比亚别生气 知乎 编辑:程序博客网 时间:2024/05/17 08:40

1.线程同步关键字volatile,synchronize,volatile修饰成员变量,synchronized修饰代码块


2.取消串行化关键字transient,当一个对象被串行化时,被transient修饰的属性变量不会被串行化,即被串行化的属性不会保存数值

private transient String name;


举例代码:

private volatile Set set = new hashSet(); 

public class TestSynchronized 
{  
    public void test1() 
    {  
          synchronized(this) 
         {  
              int i = 5;  
              while( i-- > 0) 
              {  
                   System.out.println(Thread.currentThread().getName() + " : " + i);  
                   try 
                   {  
                        Thread.sleep(500);  
                   } 
                   catch (InterruptedException ie) 
                   {  
                   }  
              }  
         }  
  }  
    public synchronized void test2() 
    {  
         int i = 5;  
         while( i-- > 0) 
         {  
              System.out.println(Thread.currentThread().getName() + " : " + i);  
              try 
              {  
                   Thread.sleep(500);  
              } 
              catch (InterruptedException ie) 
              {  
              }  
         }  
    }  
    public static void main(String[] args) 
    {  
         final TestSynchronized myt2 = new TestSynchronized();  
         Thread test1 = new Thread(  new Runnable() {  public void run() {  myt2.test1();  }  }, "test1"  );  
         Thread test2 = new Thread(  new Runnable() {  public void run() { myt2.test2();   }  }, "test2"  );  
         test1.start();;  
         test2.start();  
//         TestRunnable tr=new TestRunnable();
//         Thread test3=new Thread(tr);
//         test3.start();
    } 
}
 

test2 : 4
test2 : 3
test2 : 2
test2 : 1
test2 : 0
test1 : 4
test1 : 3
test1 : 2
test1 : 1
test1 : 0