Java多线程学习笔记1

来源:互联网 发布:excel生成sql insert 编辑:程序博客网 时间:2024/05/11 11:01

1。 volatile关键字用于告诉 VM:它不应当保存变量的私有拷贝,而应当直接与共享拷贝交互。

2。synchronized关键字确保在某一时刻,只有一个线程调用这个方法。

 

/**
 * 演示两个线程引用同一个对象与两个线程分别引用两个对象时的同步问题
 * 
 * 
@author midi13
 * 
@since 2006
 * 
 
*/

public class SynTest {
    
private String firstName, lastName;

    
private synchronized void setName(String firstName, String lastName) {
        print(
"entering setName");
        
this.firstName = firstName;
        print(
"Set first name have done firstName=" + this.firstName);
        
try {
            Thread.sleep(
1000);
        }
 catch (InterruptedException e) {
        }


        
this.lastName = lastName;
        print(
"set last name have done,and leave setName() method.firstName="
                
+ this.firstName + " lastName=" + this.lastName);
    }


    
private void print(String msg) {
        String thread 
= Thread.currentThread().getName();
        System.out.println(thread 
+ "" + msg);
    }


    
public static void main(String[] args) {
        
// 必需声明为final,否则runnable里面的run()方法不能访问。
        final SynTest test1 = new SynTest();

        
final SynTest test2 = new SynTest();
        Runnable run1 
= new Runnable() {
            
public void run() {
                test1.setName(
"arzu""guli");
            }

        }
;
        Thread threadOne 
= new Thread(run1, "threadOne");
        threadOne.start();

        
try {
            Thread.sleep(
200);
        }
 catch (InterruptedException e) {
        }

        Runnable run2 
= new Runnable() {
            
public void run() {
                
// 如果这个线程引用的是对象test2,则setName方法不需要同步,也可以保证程序达到预期目的。
                test1.setName("kang""midi");
            }

        }
;

        Thread threadTwo 
= new Thread(run2, "threadTwo");
        threadTwo.start();
        System.out.println(
"main() exit");
    }

}

原创粉丝点击