当前位置: 首页 > news >正文

两个线程交替打印字符串

每个对象都有一内置锁

wait方法 释放对象锁(不占对象锁)

sleep方法不释放对象锁(占对象锁)

优秀写法  (下面写法可能有问题,synchronized (LOCK)  提到 while前面就好了)

 1 class Info {
 2     String printStr = "i think this is ok";
 3     int i = 0;
 4 
 5     public void print() {
 6         if (i < printStr.length()) {
 7             System.out.println(Thread.currentThread().getName() + "  print   "
 8                     + printStr.charAt(i));
 9             i++;
10         }
11     }
12 }
13 
14 public class main {
15     private static Object LOCK = new Object();
16     static Info info = new Info(); // 互斥资源
17     static boolean flag = false; // false for a ,true for b
18 
19     public static void main(String[] args) {
20         // 两个线程 交替打印字符串
21         Thread a = new Thread() {
22             public void run() {
23                 while (info.i < info.printStr.length())
24                     synchronized (LOCK) {
25                         {
26                             if (false == flag) {
27                                 try {
28                                     LOCK.wait();// 在wait后的瞬间线程b得到锁
29                                 } catch (InterruptedException e) {
30                                     e.printStackTrace();
31                                 }
32                             }
33                             flag = false;
34                             info.print();
35                             LOCK.notify();// 在这里虽然唤醒了另一个线程b,但锁并没有释放
36                         }
37                     }
38             };
39         };
40         Thread b = new Thread() {
41             public void run() {
42                 while (info.i < info.printStr.length())
43                     synchronized (LOCK) {
44                         {
45                             if (true == flag) {
46                                 try {
47                                     LOCK.wait();// 在wait后的瞬间线程b得到锁
48                                 } catch (InterruptedException e) {
49                                     e.printStackTrace();
50                                 }
51                             }
52                             flag = true;
53                             info.print();
54                             LOCK.notify();// 在这里虽然唤醒了另一个线程b,但锁并没有释放
55                         }
56                     }
57             };
58         };
59         a.start();
60         b.start();
61     }
62 
63 }

 

代码1

 1 package ThreadTest;
 2 
 3 
 4 class Info
 5 {
 6     String printStr="i think this is ok";
 7     int i=0;
 8     boolean flag=false;
 9     public  void print1()
10     {
11         synchronized(this)
12         {
13             if(flag==false)
14             {
15                 try {
16                     this.wait();
17                 } catch (InterruptedException e) {
18                     e.printStackTrace();
19                 }
20             }
21         realprint();
22         flag=false;
23         notify();
24         }
25     }
26     public  void print2()
27     {
28         synchronized(this)
29         {
30             if(flag==true)
31             {
32                 try {
33                     this.wait();
34                 } catch (InterruptedException e) {
35                     e.printStackTrace();
36                 }
37             }
38         realprint();
39         flag=true;
40         notify();
41         }
42     }
43     public void realprint()
44     {
45         if(i<printStr.length())
46         {
47             System.out.println(Thread.currentThread().getName() +"  print   "+printStr.charAt(i));
48             i++;
49         }
50     }
51 }
52 class MyThread1 extends Thread
53 {
54     public Info info=null;
55     public MyThread1(Info in) {
56         this.info=in;
57     }
58     @Override
59     public void run()
60     {
61         while(info.i<info.printStr.length())
62             info.print2();
63     }
64 }
65 class MyThread2 extends Thread
66 {
67     public Info info=null;
68     public MyThread2(Info in) {
69         this.info=in;
70     }
71     @Override
72     public void run()
73     {    
74         while(info.i<info.printStr.length())
75             info.print1();
76     }
77 }
78 public class main {
79     public static void main(String[] args) {
80         //两个线程    交替打印字符串
81         Info info=new Info();                                    //互斥资源
82         MyThread1 mthread1=new MyThread1(info);
83         MyThread2 mthread2=new MyThread2(info);
84         new Thread(mthread1).start();
85         new Thread(mthread2).start();
86     }
87 
88 }

代码2

  1 package MyThreadMethod;
  2 
  3 import java.util.concurrent.locks.Condition;
  4 import java.util.concurrent.locks.ReentrantLock;
  5 
  6 class Info
  7 {
  8     String printStr="i think this is ok";
  9     int i=0;
 10     public  void print1()
 11     {
 12         if(i<printStr.length())
 13         {
 14             System.out.println(Thread.currentThread().getName() +"  print   "+printStr.charAt(i));
 15             i++;
 16         }
 17     }
 18 }
 19 public class threadMethod {
 20     ReentrantLock lock=new ReentrantLock();
 21     Condition con1=lock.newCondition();
 22     Condition con2=lock.newCondition();
 23     boolean flag=false;
 24     public class MyThread1 extends Thread 
 25     {
 26         public Info info=null;
 27         MyThread1(Info info)
 28         {
 29             this.info=info;
 30         }
 31         @Override
 32         public void run() {
 33             while(info.i<info.printStr.length())
 34             {
 35                 lock.lock();
 36                 try
 37                 {
 38                     while(flag==true)
 39                     {
 40                             try {
 41                                 con1.await();
 42                             } catch (InterruptedException e) {
 43                                 // TODO Auto-generated catch block
 44                                 e.printStackTrace();
 45                             }
 46                     }
 47                     info.print1();
 48                     flag=true;
 49                     con2.signal();
 50                 }
 51                     finally
 52                     {
 53                         lock.unlock();
 54                     }
 55                 }
 56         }
 57     }
 58     
 59     public  class MyThread2 extends Thread 
 60     {
 61         public Info info=null;
 62         MyThread2(Info info)
 63         {
 64             this.info=info;
 65         }
 66         @Override
 67         public void run() {
 68             while(info.i<info.printStr.length())
 69             {
 70                 lock.lock();
 71                 try
 72                 {
 73                     while(flag==false)
 74                     {
 75                             try {
 76                                 con2.await();
 77                             } catch (InterruptedException e) {
 78                                 // TODO Auto-generated catch block
 79                                 e.printStackTrace();
 80                             }
 81                     }
 82                     info.print1();
 83                     flag=false;
 84                     con1.signal();
 85                 }
 86                     finally
 87                     {
 88                         lock.unlock();
 89                     }
 90                 }
 91         }
 92     }
 93     public static void main(String[] args) {
 94         threadMethod tm=new threadMethod();
 95         Info info=new Info();
 96         MyThread1 thread1=tm.new MyThread1(info);
 97         MyThread2 thread2=tm.new MyThread2(info);
 98         thread1.start();
 99         thread2.start();
100         
101 
102     }
103 
104 }

 

3 不同写法

 

 1 class Info
 2 {
 3     String printStr="i think this is ok";
 4     int i=0;
 5     public void print()
 6     {
 7         if(i<printStr.length())
 8         {
 9             System.out.println(Thread.currentThread().getName() +"  print   "+printStr.charAt(i));
10             i++;
11         }
12     }
13 }
14 public class main {
15     private static Object LOCK = new Object();  
16     static Info info=new Info();                                    //互斥资源
17     static boolean flag=false;  //false for a ,true for b
18     public static void main(String[] args) {
19         //两个线程    交替打印字符串
20         Thread a=new Thread(){
21             public void run() {
22                     while(info.i<info.printStr.length())
23                         synchronized (LOCK) {
24                     {
25                         if(false==flag)
26                         {
27                             flag=true;
28                             info.print();
29                             LOCK.notify();//在这里虽然唤醒了另一个线程b,但锁并没有释放
30                             try {
31                                 if(info.i<info.printStr.length())
32                                     LOCK.wait();//在wait后的瞬间线程b得到锁  
33                             } catch (InterruptedException e) {
34                                 e.printStackTrace();
35                             }
36                         }
37                     }
38                 }
39             };
40         };
41         Thread b=new Thread(){
42             public void run() {
43                     while(info.i<info.printStr.length())
44                         synchronized (LOCK) {
45                     {
46                         if(true==flag)
47                         {
48                             flag=false;
49                             info.print();
50                             LOCK.notify();//在这里虽然唤醒了另一个线程b,但锁并没有释放
51                             try {
52                                 if(info.i<info.printStr.length())
53                                     LOCK.wait();//在wait后的瞬间线程b得到锁  
54                             } catch (InterruptedException e) {
55                                 e.printStackTrace();
56                             }
57                         }
58                     }
59                 }
60             };
61         };
62         a.start();
63         b.start();
64     }
65 
66 }

 

转载于:https://www.cnblogs.com/friends-wf/p/3658258.html

相关文章:

  • rpm包制作
  • 指针数组和指向指针的指针
  • 破碎吧,
  • Permission denied You (root) are not allowed to access to (crontab) because of pam configuration.
  • PAT 1064
  • 最大堆最小堆总结
  • Windows Server 2012 R2工作文件夹⑨:自动发现设置
  • linux下ntp时间服务器搭建
  • 5.10-17项目经理考试圆梦提分现场面授行动
  • 长文章手动分页显示代码
  • 【高德地图API】从零开始学高德JS API(一)地图展现——仙剑地图,麻点图,街景,室内图...
  • MQ:Introducing Advanced Messaging
  • Git详解之三 Git分支(第二部分)
  • [转]oracle 同义词 synonym
  • 编写一个简单的Jquery插件
  • DataBase in Android
  • echarts花样作死的坑
  • Hibernate【inverse和cascade属性】知识要点
  • Java 多线程编程之:notify 和 wait 用法
  • leetcode378. Kth Smallest Element in a Sorted Matrix
  • PHP面试之三:MySQL数据库
  • python学习笔记 - ThreadLocal
  • Selenium实战教程系列(二)---元素定位
  • 对象引论
  • 构建工具 - 收藏集 - 掘金
  • 简单易用的leetcode开发测试工具(npm)
  • 七牛云 DV OV EV SSL 证书上线,限时折扣低至 6.75 折!
  • 前端每日实战 2018 年 7 月份项目汇总(共 29 个项目)
  • 算法-图和图算法
  • (1)(1.8) MSP(MultiWii 串行协议)(4.1 版)
  • (1)虚拟机的安装与使用,linux系统安装
  • (31)对象的克隆
  • (八)光盘的挂载与解挂、挂载CentOS镜像、rpm安装软件详细学习笔记
  • (搬运以学习)flask 上下文的实现
  • (附源码)springboot掌上博客系统 毕业设计063131
  • (三)mysql_MYSQL(三)
  • (四)七种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (学习日记)2024.04.10:UCOSIII第三十八节:事件实验
  • (转载)OpenStack Hacker养成指南
  • .net framework4与其client profile版本的区别
  • .net on S60 ---- Net60 1.1发布 支持VS2008以及新的特性
  • .NET 同步与异步 之 原子操作和自旋锁(Interlocked、SpinLock)(九)
  • .NET 中使用 Mutex 进行跨越进程边界的同步
  • .NET/C# 异常处理:写一个空的 try 块代码,而把重要代码写到 finally 中(Constrained Execution Regions)
  • .net连接oracle数据库
  • @RequestBody与@ResponseBody的使用
  • @SuppressLint(NewApi)和@TargetApi()的区别
  • [ vulhub漏洞复现篇 ] JBOSS AS 4.x以下反序列化远程代码执行漏洞CVE-2017-7504
  • [ vulhub漏洞复现篇 ] ThinkPHP 5.0.23-Rce
  • [1181]linux两台服务器之间传输文件和文件夹
  • [2017][note]基于空间交叉相位调制的两个连续波在few layer铋Bi中的全光switch——
  • [AX]AX2012 R2 出差申请和支出报告
  • [C++]拼图游戏
  • [C进阶] 数据在内存中的存储——浮点型篇
  • [Django开源学习 1]django-vue-admin