java程序运行结果

下面这段代码的运行结果是:AB.B

分析原因:也就是说在你的operate()方法中,参数是引用传递,也就是x,y分别为a,b引用的拷贝,在方法中,你给x追加了值,也就相应的改变了a的值,但是第二条语句:
y = x; 确实将引用y指向了另外一个对象x,这样y就和b指向不同的两个对象了,当然b的值也就不会改变了。

public class test2 {
    public static void main(String sgf[]){
        StringBuffer a=new StringBuffer("A");
        StringBuffer b=new StringBuffer("B");
        operate(a,b);
        System.out.println(a+"."+b);
    }
    static void operate(StringBuffer x,StringBuffer y){
        x.append(y);
        y=x;
    }
}

下面这段代码运行结果是:14

public class test3 {
    String str = "1";
    String[] strArr = {"2"};
    public static void main(String[] args)
    {
        test3 app = new test3();
        app.operate(app.str, app.strArr);
        System.out.println(app.str +app.strArr[0]);
    }
    static void operate(String str, String[] strArr)
    {
        str = new String("3");
        strArr[0] = new String("4");
    }
}

下面这段代码运行结果是:2 24 46 6

分析:因为线程中用到了synchronized同步,所以在三个线程中的result和data的值分别是:2,2;4,4;6,6

然后注意到System.out.print(result+" "+ data);所以最终结果是2 24 46 6

public class test1 {
    private int data;
    int result=0;
    public void m(){
        result+=2;
        data+=2;
        System.out.print(result+" "+ data);
    }
}

class ThreadExample extends Thread{
    private test1 mv;
    public ThreadExample(test1 mv){
        this.mv=mv;
    }
    public void run(){
        synchronized (mv){
            mv.m();
        }
    }
}
class ThreadTest{
    public static void main(String args[]){
        test1 mv=new test1();
        Thread t1=new ThreadExample(mv);
        Thread t2=new ThreadExample(mv);
        Thread t3=new ThreadExample(mv);
        t1.start();
        t2.start();
        t3.start();
    }
}
原文地址:https://www.cnblogs.com/lijingran/p/8885871.html