温馨提示×

温馨提示×

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

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

Java中怎么利用多线性同步读写数据

发布时间:2021-07-23 16:40:34 来源:亿速云 阅读:132 作者:Leah 栏目:编程语言

Java中怎么利用多线性同步读写数据,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

  1. public class SynTest ...{  

  2. private String firstName, lastName;  

  3. private synchronized String getName() ...{  

  4. String result = firstName + " " + lastName;  

  5. return result;  

  6. }  

  7. private synchronized void setName(String firstName,
     String lastName) ...{  

  8. print("entering setName");  

  9. this.firstName = firstName;  

  10. print("Set first name have done firstName=" + 
    this.firstName);  

  11. try ...{  

  12. Thread.sleep(1000);  

  13. } catch (InterruptedException e) ...{  

  14. }  

  15. this.lastName = lastName;  

  16. print("set last name have done,and leave setName() 
    method.firstName="  

  17. + this.firstName + " lastName=" + this.lastName);  

  18. }  

  19. private static void print(String msg) ...{  

  20. String thread = Thread.currentThread().getName();  

  21. System.out.println(thread + ": " + msg);  

  22. }  

  23. public static void main(String[] args) ...{  

  24. // 必需声明为final,否则runnable里面的run()方法不能访问。  

  25. final SynTest test1 = new SynTest();  

  26. // 设置初始值  

  27. test1.setName("arzu", "guli");  

  28. Runnable run1 = new Runnable() ...{  

  29. public void run() ...{  

  30. test1.setName("kang", "midi");  

  31. }  

  32. };  

  33. // 修改名字线程  

  34. Thread threadOne = new Thread(run1, "threadOne");  

  35. threadOne.start();  

  36. try ...{  

  37. Thread.sleep(200);  

  38. } catch (InterruptedException e) ...{  

  39. }  

  40. Runnable run2 = new Runnable() ...{  

  41. public void run() ...{  

  42. print("读取" + test1.getName());  

  43. }  

  44. };  

  45. // 读取名字线程  

  46. Thread threadTwo = new Thread(run2, "threadTwo");  

  47. threadTwo.start();  

  48. System.out.println("main() exit");  

  49. }  

看完上述内容,你们掌握Java中怎么利用多线性同步读写数据的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

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

AI