程序员社区

第七章 线程的同步

1.多线程共享数据|发的问题

    1.1.模拟网络购票

 1 public class Site implements Runnable{
 2     private int cath=10;//总共有多少章票
 3     private int num=0;//记录买到的票数
 4     @Override
 5     public void run() {
 6       while (true){
 7           //没票是跳出循环
 8           if (cath<=0){
 9               break;
10           }
11           //第二步:修改数据
12           num++;
13           cath--;
14           //第三步,模拟网络延迟
15           try {
16               Thread.sleep(500);
17           } catch (InterruptedException e) {
18               e.printStackTrace();
19           }
20           //第四步显示信息
21           System.out.println(Thread.currentThread().getName()+"抢到第"+num+"章票,剩余"+cath+"票");
22       }
23     }
24 }

 1 /**
 2  * 测试类
 3  */
 4 public class Texts {
 5     public static void main(String[] args) {
 6        Thread th1=new Thread(new Site(),"王刚");
 7         Thread th2=new Thread(new Site(),"黄牛");
 8         Thread th3=new Thread(new Site(),"团购");
 9         th1.start();
10         th2.start();
11         th3.start();
12     }
13 }

 第七章  线程的同步插图                        当多个线程共享同一资源时,一个线程未完成全部操作的时候其他线程修改的数据,造成数据不安全问题。

2.同步方法的网络购票

 1 public class Site implements Runnable{
 2     private int cath=10;//总共有多少章票
 3     private int num=0;//记录买到的票数
 4     private boolean f=true;
 5     @Override
 6     public void run() {
 7       while (f){
 8           sion();
 9       }
10     }
//同步方法
11 public synchronized void sion(){ 12 //没票是跳出循环 13 if (cath<=0){ 14 f=false; 15 return; 16 } 17 //第二步:修改数据 18 num++; 19 cath--; 20 //第三步,模拟网络延迟 21 try { 22 Thread.sleep(500); 23 } catch (InterruptedException e) { 24 e.printStackTrace(); 25 } 26 //第四步显示信息 27 System.out.println(Thread.currentThread().getName()+"抢到第"+num+"章票,剩余"+cath+"票"); 28 } 29 }
/**
* 测试类
*/
public class Texts {
public static void main(String[] args) {
Site si=new Site();
Thread th1=new Thread(si,"王刚");
Thread th2=new Thread(si,"黄牛");
Thread th3=new Thread(si,"团购");
th1.start();
th2.start();
th3.start();
}
}

第七章  线程的同步插图1

第七章  线程的同步插图2                         效果和同步方法一样  第七章  线程的同步插图3

 多个并发线程访问同一资源的同步代码块时

       第七章  线程的同步插图4

 

 3.线程的安全类型

第七章  线程的同步插图5        第七章  线程的同步插图6

 

  4.常见的类型比较

第七章  线程的同步插图7 

 

赞(0) 打赏
未经允许不得转载:IDEA激活码 » 第七章 线程的同步

相关推荐

  • 暂无文章

一个分享Java & Python知识的社区