//同步分为:同步块和同步方法。
//每个class都有一个锁或叫做监视器
// 1.同步块的实现:
class SellTickets implements Runnable{
public int i = 50;
public void run(){
/*为了避免时间轮换导致的结果不可预料,就需要给方法加锁
就可以避免出现class_5_54的数据超出范围现象*/
synchronized (this) { //此处称为 同步块
while( i > 0){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("i : "+ i);
i--;
}
}
}
}
// 2.同步方法的实现:
class SellTickets2 implements Runnable{
public int i = 50;
public void run(){
this.syn();
}
public synchronized void syn(){ //此处称为 同步方法
while(i > 0){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("i : "+ i);
i--;
}
}
}
public class Thread_Test {
public static void main(String [] args){
//用同步块来创建多线程
SellTickets mt = new SellTickets();
Thread t1 = new Thread(mt);
Thread t2 = new Thread(mt);
Thread t3 = new Thread(mt);
Thread t4 = new Thread(mt);
t1.start();
t2.start();
t3.start();
t4.start();
//用同步方法来创建多线程
SellTickets2 st = new SellTickets2();
Thread tt1 = new Thread(st);
Thread tt2 = new Thread(st);
Thread tt3 = new Thread(st);
Thread tt4 = new Thread(st);
tt1.start();
tt2.start();
tt3.start();
tt4.start();
}
}