您的位置:首页 > 编程语言 > Java开发

java里线程同步方法二:同步函数

2016-03-31 13:30 453 查看
同步函数代码实例如下:

class ThreadDemo1 {
public static void main(String[] args) {
TestThread tt = new TestThread();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();

}
}

class TestThread implements Runnable {
int tickets = 100;

public void run() {
while (true) {
sale();
}
}

public synchronized void sale() {
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (Exception e) {
}
System.out.println(Thread.currentThread().getName()
+ " is saling ticket " + tickets--);
}
}
}


运行结果:



通过运行结果可知四个线程得到了同步。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: