Java线程同步引用有很多的使用范围,在不断的使用中我们有很多的知识需要学习。我们可以在计算机上运行各种计算机软件程序。每一个运行的程序可能包括多个独立运行的线程。
- 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");
- }
- }
以上就是对Java线程同步引用的详细介绍。
【编辑推荐】