建立如下的测试类
public class Tobj extends Thread {
public static Object bb=1;
public int v1;
public Tobj(int aa){
v1=aa;
}
public void run(){
testSY(1);
// testSY2();
}
//方法1 普通方法 同时只能有一个对象方法访问testSY
//无法限制不同线程对testSY的访问
public synchronized void testSY(int p1) {
System.out.println("thread:"+p1);
try{
Thread.currentThread().sleep(10000);
}catch(Exception e){}
System.out.println("thread"+v1+",sleep ok");
}
//方法2 使用静态方法,同时只能有一个对象方法或线程访问testSY1
public static synchronized void testSY1(int v1){
System.out.println("static thread:"+v1);
try{
Thread.currentThread().sleep(1000);
}catch(Exception e){}
System.out.println("static thread"+v1+",sleep ok");
}
//方法3 使用类变量
public void testSY2(){
//同时只能有一个对象方法或是单个线程访问该代码段
synchronized (bb){
System.out.println("thread:"+v1);
try{
Thread.currentThread().sleep(1000);
}catch(Exception e){}
System.out.println("thread"+v1+",sleep ok");
}
}
}
测试的代码就不写了,可以根据项目需要选择不同的方法
public class Tobj extends Thread {
public static Object bb=1;
public int v1;
public Tobj(int aa){
v1=aa;
}
public void run(){
testSY(1);
// testSY2();
}
//方法1 普通方法 同时只能有一个对象方法访问testSY
//无法限制不同线程对testSY的访问
public synchronized void testSY(int p1) {
System.out.println("thread:"+p1);
try{
Thread.currentThread().sleep(10000);
}catch(Exception e){}
System.out.println("thread"+v1+",sleep ok");
}
//方法2 使用静态方法,同时只能有一个对象方法或线程访问testSY1
public static synchronized void testSY1(int v1){
System.out.println("static thread:"+v1);
try{
Thread.currentThread().sleep(1000);
}catch(Exception e){}
System.out.println("static thread"+v1+",sleep ok");
}
//方法3 使用类变量
public void testSY2(){
//同时只能有一个对象方法或是单个线程访问该代码段
synchronized (bb){
System.out.println("thread:"+v1);
try{
Thread.currentThread().sleep(1000);
}catch(Exception e){}
System.out.println("thread"+v1+",sleep ok");
}
}
}
测试的代码就不写了,可以根据项目需要选择不同的方法