标签:tst oid static 同步代码块 ace art -- public ted
初学java多线程,在用synchronize关键字修饰同步代码块时,运行代码发现不能交替卖票。 以下是初始代码
package com.itheima.Test; public class Test1a { public static void main(String[] args) { Ticket1a t1=new Ticket1a(); new Thread(t1,"A").start(); new Thread(t1,"B").start(); new Thread(t1,"C").start(); } } class Ticket1a implements Runnable{ int ticket=100; @Override public void run() { synchronized (Ticket1a.class) { while (true) { if (ticket<=0) { break; } try { Thread.sleep(20); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+" sold "+(ticket--)); } } } }
运行结果:
A sold 100 A sold 99 A sold 98 A sold 97 A sold 96 A sold 95 A sold 94 A sold 93 A sold 92 A sold 91 . . . A sold 10 A sold 9 A sold 8 A sold 7 A sold 6 A sold 5 A sold 4 A sold 3 A sold 2 A sold 1
虽然解决了线程的安全问题,但是不能实现三个窗口交替卖票。后来仔细一看,是synchronize关键字修饰的代码块位置不对,相当于修饰了同步方法。
更改后:
@Override public void run() { while (true) { synchronized (Ticket1a.class) { if (ticket<=0) { break; } try { Thread.sleep(20); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+" sold "+(ticket--)); } } }
这样就完成了线程安全的小测试。
代码布局实在太乱没来得及改......
标签:tst oid static 同步代码块 ace art -- public ted
原文地址:https://www.cnblogs.com/springa/p/12622365.html