继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

多线程(线程安全问题)学习笔记

千岁不倒翁
关注TA
已关注
手记 362
粉丝 60
获赞 386

多线程并发操作同一数据时, 就有可能出现线程安全问题* 使用同步技术可以解决这种问题, 把操作数据的代码进行同步, 不要多个线程一起操作            public class Demo2_Synchronized {                /**                 * @param args                 * 需求:铁路售票,一共100张,通过四个窗口卖完.                 */                public static void main(String[] args) {                    TicketsSeller t1 = new TicketsSeller();                    TicketsSeller t2 = new TicketsSeller();                    TicketsSeller t3 = new TicketsSeller();                    TicketsSeller t4 = new TicketsSeller();                    t1.setName("窗口1");                    t2.setName("窗口2");                    t3.setName("窗口3");                    t4.setName("窗口4");                    t1.start();                    t2.start();                    t3.start();                    t4.start();                }            }            class TicketsSeller extends Thread {                private static int tickets = 100;                static Object obj = new Object();                public TicketsSeller() {                    super();                }                public TicketsSeller(String name) {                    super(name);                }                public void run() {                    while(true) {                        synchronized(obj) {                            if(tickets <= 0)                                 break;                            try {                                Thread.sleep(10);//线程1睡,线程2睡,线程3睡,线程4睡                            } catch (InterruptedException e) {                                e.printStackTrace();                            }                            System.out.println(getName() + "...这是第" + tickets-- + "号票");                        }                    }                }            }

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP