使用runnable可以将资源共享,但是在延迟时,还是会出现错误:
class MyThread implements Runnable
{private int iTickets = 5 ;
public void run(){
for(int i=0;i<100;i++){
if(iTickets > 0){
try{
Thread.sleep(300) ;
}catch(InterruptedException e){
e.printStackTrace() ;
}
System.out.println("卖票:" + iTickets--) ;
}
}
}
};
public class SyncDemo01
{
public static void main(String args[]){
MyThread mt1 = new MyThread() ;
Thread t1 = new Thread(mt1) ;
Thread t2 = new Thread(mt1) ;
Thread t3 = new Thread(mt1) ;
t1.start() ;
t2.start() ;
t3.start() ;
}
}
同步代码块:
synchronized(需同步的对象){
同步代码块;
}
※同步对象通常用this表示
class MyThread implements Runnable
{
private int iTickets = 5 ;
public void run(){
for(int i=0;i<100;i++){
synchronized(this){
if(iTickets > 0){
try{
Thread.sleep(300) ;
}catch(InterruptedException e){
e.printStackTrace() ;
}
System.out.println("卖票:" + iTickets--) ;
}
}
}
}
};
public class SyncDemo02
{
public static void main(String args[]){
MyThread mt1 = new MyThread() ;
Thread t1 = new Thread(mt1) ;
Thread t2 = new Thread(mt1) ;
Thread t3 = new Thread(mt1) ;
t1.start() ;
t2.start() ;
t3.start() ;
}
}
可以使用synchronized关键字将方法声明成同步方法
格式:synchronized 方法返回值 方法名称(参数列表){}
二、死锁
资源共享式需要进行同步
程序中过多的同步会产生死锁