public class App {
public static void main(String[] args) {
ThreadSafe t=new ThreadSafe();
Thread aThread=new Thread(t);
Thread bThread=new Thread(t);
Thread cThread=new Thread(t);
Thread dThread=new Thread(t);
aThread.start();
bThread.start();
cThread.start();
dThread.start();
}
}
public class ThreadSafe implements Runnable{
int num=10;
public void run() {
while(true) {
if(num>0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
System.out.println("tickets:"+num--);
}
}
}
}
tickets:10
tickets:9
tickets:10
tickets:8
tickets:7
tickets:6
tickets:5
tickets:4
tickets:3
tickets:3
tickets:2
tickets:1
tickets:0
tickets:-2
tickets:-1
//synchronized同步资源
public class ThreadSafe implements Runnable{
int num=10;
public synchronized void run() {
while(true) {
if(num>0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
System.out.println("tickets:"+num--);
}
}
}
tickets:10
tickets:9
tickets:8
tickets:7
tickets:6
tickets:5
tickets:4
tickets:3
tickets:2
tickets:1
还没有评论,来说两句吧...