ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
~~~ package thread.a5; public class Test { public static void main(String[] args) { Xc8 xc81=new Xc8(); Thread ee = new Thread(xc81); ee.start(); Xc8 xc82=new Xc8(); Thread ff = new Thread(xc82); ff.start(); } } class Xc8 implements Runnable { public static int chepiao = 100;//static只执行一次,共享100张票,否则会是200张 public void run() { while (true) { if (chepiao > 0) { System.out.println("第"+Thread.currentThread().getName()+"个车站正在卖第"+(101-chepiao)+"张车票"); --chepiao; } else { break; } } } } ~~~ ![](https://box.kancloud.cn/ec8fb29e0c4f9972e0707d76f362a12b_370x94.png) 程序还是有问题,因为程序执行到一半,另一个线程也开启了 优化代码如下 ~~~ package thread.a5; public class Test1 { public static void main(String[] args) { Xc9 xc9=new Xc9(); Thread ee = new Thread(xc9); ee.start(); Thread ff = new Thread(xc9); ff.start(); } } class Xc9 implements Runnable { public static int chepiao = 100; String aa = new String("1"); //字符串随意定义,定义在函数上边 //synchronized 的作用是,让它所管辖的代码部分,要么全部执行完,要么全部不执行 public void run() //synchronized修饰函数不需要字符串,相当于默认是this { while (true) { synchronized (aa) //既可以修饰代码块,又可以修饰函数 { if (chepiao > 0) { System.out.println("第"+Thread.currentThread().getName()+"个车站正在卖第"+(101-chepiao)+"张车票"); --chepiao; } else { break; } } } } } ~~~ ![](https://box.kancloud.cn/599aa5da53f3a50c5da2f0f16ce3367f_488x171.png)