您的位置:首页 > 其它

多线程 《多线程操作同一变量》

2014-05-08 16:26 92 查看
【代码说明】

两个线程“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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多线程