写在开始
卖票场景:
多线程共同卖票,总票数在多个卖票窗口共享
实现方式:
1继承Thread类;
2实现Runnable接口
正文开始
方式1 Thread继承
package com.example.demo; /** * @Description: * @Author:tianminghai * @Date:2:55 PM 2018/10/24 */ public class ThreadDemo extends Thread { private static int ticket = 100000; public ThreadDemo() { } @Override public void run() { while (true) { synchronized ("") { if (ticket > 0) { ticket--; System.out.println("当前线程号:" + Thread.currentThread().getId() + "剩余票数:" + this.ticket); } } } } }
方式2 实现Runnable
package com.example.demo; /** * @Date:2:55 PM 2018/10/24 */ public class ThreadDemo2 implements Runnable { private static int ticket = 100; public ThreadDemo2() { } @Override public void run() { while (true) { synchronized ("") { if (ticket > 0) { ticket--; System.out.println("当前线程号:" + Thread.currentThread().getId() + " 剩余票数:" + this.ticket); } } } } }
Client端
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); for (int i = 0; i < 30; i++) { // 方式1 new ThreadDemo().start(); // 方式2 new Thread(new ThreadDemo2()).start(); } } }
需要注意的点
1由于总票数在多个卖票窗口共享,所以ticket应设为静态变量;
2下面两种多线程实现方式都要使用synchronized进行封装,且封装的粒度要小不可以包含while等代码段
原文地址:https://www.cnblogs.com/tianmh/p/9844538.html
时间: 2024-11-08 21:47:17