java正在同步来自不同对象{已编辑}的线程
JAVA-同步来自不同对象的线程。参考下面的例子;如果它只有一个目标,那么它工作得很好;但是,如果我使用2,它不会像预期的那样工作;在我的用例中,我有20个对象,它们具有不同的字符串值,并且都同时运行;同步块没有得到尊重
public class temp {
synchronized void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
temp t;
MyThread1(temp t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
temp t;
MyThread2(temp t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[]){
temp obj = new temp();//only one object
temp obj2 = new temp();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj2);
t1.start();
t2.start();
}
}
输出: 5. 100 200 10 15 300 400 20 25 五百
但是如果我使用一个temp实例
class TestSynchronization1{
public static void main(String args[]){
temp obj = new temp();//only one object
//temp obj2 = new temp();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
输出: 5. 10 15 20 25 100 200 300 400 五百
共 (0) 个答案