- 论坛徽章:
- 0
|
Java多线程同步应用
[Java]代码- /**
- * Synchronized同步关键字
- * @author luoguansong lgsstart89@163.com
- */
- public class SynchronizedDemo implements Runnable{
- private int count = 20;
-
- public void run() {
- while(true){
- synchronized(this){
- if (count > 0) {
- System.out.println(Thread.currentThread().getName()+ "正在卖票,还剩余"+this.count--+"张票");
- }else{
- System.out.println(Thread.currentThread().getName()+"票卖完了");
- break;
- }
- try{
- wait(500);
- }catch (Exception e) {
- System.out.println(e.getMessage());
- }
- }
- }
- }
-
- public static void main(String[] args) {
- SynchronizedDemo h1 = new SynchronizedDemo();
- Thread h2=new Thread(h1, "1号窗口");
- Thread h3=new Thread(h1, "2号窗口");
- Thread h4=new Thread(h1, "3号窗口");
-
- h2.start();
- h3.start();
- h4.start();
- }
- }
复制代码 |
|