/*
同步的前题:
1.必须要有两个或以上线程
2.必须是多个线程使用一个锁
优点:解决多线程安全问题
弊端:多个线程判断锁,消耗资源
*/
package pack;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
public static void sys(Object obj) {
System.out.println(obj);
}
}
/*class Ticket implements Runnable { //同步代码块
Object obj = new Object();
private int tick = 100;
public void run() {
while(true) {
synchronized(obj) {
if(tick>0)
Main.sys(Thread.currentThread().getName()+"---"+tick--);
}
}
}
}*/
class Ticket implements Runnable { //同步函数
Object obj = new Object();
private int tick = 100;
public void run() {
while(true) {
show();
}
}
public synchronized void show() {
if(tick>0)
Main.sys(Thread.currentThread().getName()+"---"+tick--);
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/sjtu_chenchen/article/details/46756965