Java线程同步引用的基本代码介绍

发布时间:2021-09-17 16:25:03 作者:chen
来源:亿速云 阅读:88

这篇文章主要讲解了“Java线程同步引用的基本代码介绍”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Java线程同步引用的基本代码介绍”吧!

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线程同步引用的基本代码介绍”的内容了,经过本文的学习后,相信大家对Java线程同步引用的基本代码介绍这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. PHP引用符&的用法介绍
  2. java中的线程同步介绍

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:如何理解ajax中的async属性值同步和异步及同步和异步区别

下一篇:Java出现Error: Java heap space错误的解决方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》