赞
踩
一、创建线程的方法是实现runnable,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法
- *********************************/
- //多个线程同时操作一个类
- //火车票
- public class TestTread4 implements Runnable{
-
- //票数
- private int ticketNums = 10;
- @Override
- public void run() {
-
- while (true) {
- if (ticketNums <= 0) {
- break;
- }
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName()+"--->拿到了第"+ticketNums-- +"张票");
- }
-
- }
-
- public static void main(String[] args) {
- TestTread4 testTread4 = new TestTread4();
-
- new Thread(testTread4, "小明").start();
- new Thread(testTread4,"老师").start();
- new Thread(testTread4,"黄牛").start();
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱.
加上锁就搞定
- public class TestTread4 implements Runnable{
-
- //票数
- private int ticketNums = 10;
- @Override
- public synchronized void run() {
-
- while (true) {
- if (ticketNums <= 0) {
- break;
- }
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName()+"--->拿到了第"+ticketNums-- +"张票");
- }
-
- }
-
- public static void main(String[] args) {
- TestTread4 testTread4 = new TestTread4();
-
- new Thread(testTread4, "小明").start();
- new Thread(testTread4,"老师").start();
- new Thread(testTread4,"黄牛").start();
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
当有200人抢100张票
- public class TicketRunnable implements Runnable {
-
- /**
- * 总票数
- */
- private final int ticketSize = 100;
-
- /**
- * 抢票人数
- */
- private final int peopleSize = 200;
-
- /**
- * 票数
- */
- private int ticketNum;
-
- /**
- * 人数
- */
- private int peopleNum;
-
- @Override
- public void run() {
- while(ticketNum < ticketSize && peopleNum < peopleSize){
- synchronized (this){
- if(ticketNum < ticketSize && peopleNum < peopleSize){
- if((int)(Math.random() * 20) % 2 == 1){
- System.out.println(Thread.currentThread().getName() + "第" + (++peopleNum) + "个人抢到第" + (++ticketNum) + " 张票");
- try {
- Thread.sleep(100);
- }catch (Exception e){
- e.printStackTrace();
- }
- }else {
- System.out.println(Thread.currentThread().getName() + "第" + (++peopleNum) + " 个人未抢到票");
- }
- }
- }
- }
-
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- public class TestTicket {
- public static void main(String[] args) {
- TicketRunnable tr = new TicketRunnable();
- Thread t1 = new Thread(tr , "窗口A");
- Thread t2 = new Thread(tr , "窗口B");
- Thread t3 = new Thread(tr , "窗口C");
- Thread t4 = new Thread(tr , "窗口D");
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。