多线程 《多线程操作同一变量》
2014-05-08 16:26
92 查看
【代码说明】
两个线程“Window1”和“Window2”操作同一变量ticketCount(卖票)。
【代码示例】
1、MyThread.java
2、TestMyThread.java
【运行结果】
Window 1 sell one ticket,remainder ticket count is : 9
Window 1 sell one ticket,remainder ticket count is : 7
Window 1 sell one ticket,remainder ticket count is : 6
Window 2 sell one ticket,remainder ticket count is : 8
Window 2 sell one ticket,remainder ticket count is : 4
Window 2 sell one ticket,remainder ticket count is : 3
Window 2 sell one ticket,remainder ticket count is : 2
Window 2 sell one ticket,remainder ticket count is : 1
Window 2 sell one ticket,remainder ticket count is : 0
Window 1 sell one ticket,remainder ticket count is : 5
两个线程“Window1”和“Window2”操作同一变量ticketCount(卖票)。
【代码示例】
1、MyThread.java
package com.wcs.java.thread; public class MyThread implements Runnable{ private int ticketCount; public MyThread(int ticketCount) { this.ticketCount = ticketCount; } public synchronized int sellTicket() { return --ticketCount; } @Override public void run() { while(ticketCount > 0) { System.out.println(Thread.currentThread().getName() + " sell one ticket,remainder ticket count is : " + sellTicket()); } } }
2、TestMyThread.java
package com.wcs.java.thread; public class TestMyThread { public static void main(String[] args) { MyThread myThread = new MyThread(10); Thread t1 = new Thread(myThread, "Window 1"); Thread t2 = new Thread(myThread, "Window 2"); t1.start(); t2.start(); } }
【运行结果】
Window 1 sell one ticket,remainder ticket count is : 9
Window 1 sell one ticket,remainder ticket count is : 7
Window 1 sell one ticket,remainder ticket count is : 6
Window 2 sell one ticket,remainder ticket count is : 8
Window 2 sell one ticket,remainder ticket count is : 4
Window 2 sell one ticket,remainder ticket count is : 3
Window 2 sell one ticket,remainder ticket count is : 2
Window 2 sell one ticket,remainder ticket count is : 1
Window 2 sell one ticket,remainder ticket count is : 0
Window 1 sell one ticket,remainder ticket count is : 5
相关文章推荐
- 多线程中对全局变量(整型类型)是否需要同步操作
- 多线程环境下对变量的读写操作的原子性问题(一道百度笔试题引发的思考)
- 多线程下变量原子操作的几种方法
- [转] 多线程下变量-gcc原子操作 __sync_fetch_and_add等
- 多线程环境下对变量的读写操作的原子性问题
- 多线程中对全局变量(整型类型)是否需要同步操作
- 多线程环境下对变量的读写操作的原子性问题(一道百度笔试题引发的思考)
- 多线程环境下对变量的读写操作的原子性问题(一道百度笔试题引发的思考)
- 多线程下变量-原子操作 __sync_fetch_and_add等等
- java进阶(七)------多线程---多线程操作同一变量
- 多线程下变量-原子操作 __sync_fetch_and_add等等
- java进阶(七)------多线程---多线程操作同一变量
- 多线程下变量-原子操作 __sync_fetch_and_add等等
- 多线程中对全局变量(整型类型)是否需要同步操作
- c++多线程操作全局变量的锁的问题
- 多线程环境下对变量的读写操作的原子性问题
- 多线程操作一个变量示例
- Java多线程操作局部变量与全局变量
- Java多线程复习与巩固(八)--原子性操作与原子变量
- 多线程中对全局变量(整型类型)是否需要同步操作