在网上看了一些多线程的文章,经过实测发现与文章解释有所出入,在这里发个文,更正一下,方便大家去伪存真。欢迎大家指正。
一、举个经典列子:卖车票
很多文章都说Thread无法实现资源共享,给出的代码如下:
public class MyThreadWithExtends extends Thread {
private int tickets = 10;
@Override
public void run() {
public void run() {
for (int i = 0; i <= 100; i++) {
if(tickets>0){
System.out.println(Thread.currentThread().getName()+"--卖出票:" + tickets--);
}
}
}
public static void main(String[] args) {
MyThreadWithExtends thread1 = new MyThreadWithExtends();
MyThreadWithExtends thread2 = new MyThreadWithExtends();
MyThreadWithExtends thread3 = new MyThreadWithExtends();
if(tickets>0){
System.out.println(Thread.currentThread().getName()+"--卖出票:" + tickets--);
}
}
}
public static void main(String[] args) {
MyThreadWithExtends thread1 = new MyThreadWithExtends();
MyThreadWithExtends thread2 = new MyThreadWithExtends();
MyThreadWithExtends thread3 = new MyThreadWithExtends();