java——多线程之线程安全

今天药忘吃喽~ 2023-06-06 07:59 117阅读 0赞
  1. public class App {
  2. public static void main(String[] args) {
  3. ThreadSafe t=new ThreadSafe();
  4. Thread aThread=new Thread(t);
  5. Thread bThread=new Thread(t);
  6. Thread cThread=new Thread(t);
  7. Thread dThread=new Thread(t);
  8. aThread.start();
  9. bThread.start();
  10. cThread.start();
  11. dThread.start();
  12. }
  13. }
  14. public class ThreadSafe implements Runnable{
  15. int num=10;
  16. public void run() {
  17. while(true) {
  18. if(num>0) {
  19. try {
  20. Thread.sleep(100);
  21. } catch (InterruptedException e) {
  22. // TODO 自动生成的 catch 块
  23. e.printStackTrace();
  24. }
  25. System.out.println("tickets:"+num--);
  26. }
  27. }
  28. }
  29. }
  30. tickets:10
  31. tickets:9
  32. tickets:10
  33. tickets:8
  34. tickets:7
  35. tickets:6
  36. tickets:5
  37. tickets:4
  38. tickets:3
  39. tickets:3
  40. tickets:2
  41. tickets:1
  42. tickets:0
  43. tickets:-2
  44. tickets:-1
  45. //synchronized同步资源
  46. public class ThreadSafe implements Runnable{
  47. int num=10;
  48. public synchronized void run() {
  49. while(true) {
  50. if(num>0) {
  51. try {
  52. Thread.sleep(100);
  53. } catch (InterruptedException e) {
  54. // TODO 自动生成的 catch 块
  55. e.printStackTrace();
  56. }
  57. System.out.println("tickets:"+num--);
  58. }
  59. }
  60. }
  61. tickets:10
  62. tickets:9
  63. tickets:8
  64. tickets:7
  65. tickets:6
  66. tickets:5
  67. tickets:4
  68. tickets:3
  69. tickets:2
  70. tickets:1

发表评论

表情:
评论列表 (有 0 条评论,117人围观)

还没有评论,来说两句吧...

相关阅读