JavaSE 多线程(2)同步函数

来源:互联网 发布:java 内存缓存 编辑:程序博客网 时间:2024/06/05 00:12
同步函数
package ticket;


class Ticket1 implements Runnable{//extends Thread{
private  int num=100;
//Object obj=new Object();
public void run(){ //synchronized void run(){
// 不要把不该同步的代码同步,此时会出现问题,在这种情况下,0线程进来永远也出不去
//可以把需要同步的的代码封装起来,在加同步关键字,然后在run方法中调用。
while(true){
show();
}
}
public synchronized void show(){
if (num>0) {
try {Thread.sleep(10);} catch (InterruptedException e) {}
System.out.println(Thread.currentThread().getName()+"----sale...."+num--);
}
}

}
public class synFunctionLockDemo {
public static void main(String[] args) {
Ticket1 t=new Ticket1();//创建一个线程任务
//Ticket tt=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();
}




}




同步函数使用的锁是this


同步函数和同步代码块的区别:
  同步函数的锁是固定的this
  同步代码块的锁是任意的对象。
建议使用同步代码块。
package ticket;


class Ticket1 implements Runnable{//extends Thread{
private  int num=100;
// Object obj=new Object();
boolean falg=true;

public void run(){
if (falg)
while(true){
synchronized(this){
if (num>0) {
try {Thread.sleep(10);} catch (InterruptedException e) {}
System.out.println(Thread.currentThread().getName()+"----obj...."+num--);
}
}
}
else
while(true)
this.show();
}
public synchronized void show(){
if (num>0) {
try {Thread.sleep(10);} catch (InterruptedException e) {}
System.out.println(Thread.currentThread().getName()+"----show...."+num--);
}
}

}
public class synFunctionLockDemo {
public static void main(String[] args) {
Ticket1 t=new Ticket1();//创建一个线程任务
//Ticket tt=new Ticket();

Thread t1=new Thread(t);
Thread t2=new Thread(t);

t1.start();
try {Thread.sleep(10);} catch (InterruptedException e) {}
t.falg=false;
t2.start();

}


}
静态的同步函数使用的锁是 该函数所属的字节码文件对象
可以用getClass 方法获取,也可以用当前 类名.class 表示


package ticket;


class Ticket1 implements Runnable{//extends Thread{
private static  int num=100;
// Object obj=new Object();
boolean falg=true;

public void run(){
if (falg)
while(true){
synchronized(Ticket.class){//(this.getClass()){
if (num>0) {
try {Thread.sleep(10);} catch (InterruptedException e) {}
System.out.println(Thread.currentThread().getName()+"----obj...."+num--);
}
}
}
else
while(true)
this.show();
}
public static synchronized void show(){
if (num>0) {
try {Thread.sleep(10);} catch (InterruptedException e) {}
System.out.println(Thread.currentThread().getName()+"----show...."+num--);
}
}

}
public class synFunctionLockDemo {
public static void main(String[] args) {
Ticket1 t=new Ticket1();//创建一个线程任务
//Ticket tt=new Ticket();

Thread t1=new Thread(t);
Thread t2=new Thread(t);

t1.start();
try {Thread.sleep(10);} catch (InterruptedException e) {}
t.falg=false;
t2.start();
}

}




0 0
原创粉丝点击