Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6922945
  • 博文数量: 700
  • 博客积分: 10821
  • 博客等级: 上将
  • 技术积分: 12011
  • 用 户 组: 普通用户
  • 注册时间: 2005-12-02 10:41
个人简介

大数据、ML、AI、云计算openstack、Linux、SpringCloud。

文章分类

全部博文(700)

分类: Java

2013-12-19 17:26:55

private static和public static的比较,区别在于修改的范围不同,但作用域都是全局的即整个进程内共享,与具体线程无关。
以下是测试代码:


声明静态内部变量的抽象类
package atest.privateStatic;

public abstract class TypeObject {

    private static int id = 0;   // private static 变量 by hiya
    private int typeId;
    private String word;

    protected TypeObject(String word){
        id = id + 1;
        this.typeId = id;
        this.word = word;
        System.out.println("id=" + id + "  word=" + word);

    }

}

// 具体实现类
package atest.privateStatic;

public class StringType extends TypeObject {

    protected StringType(String word) {
        super(word);
        // TODO 自動生成されたコンストラクター?スタブ
    }

}

多线程间测试类

package atest.privateStatic;

public class PrivateStaticTest {

    /**
     * [メソッドの説明を書きましょう]
     * @param args
     */
    public static void main(String[] args) {
        // TODO 自動生成されたメソッド?スタブ

        PrivateStaticTest a = new PrivateStaticTest();

        Test1 test1 = a.new Test1();
        Thread t1 = new Thread(test1);
        t1.start();
        try {
            Thread.sleep(1000);
        } catch (Exception e){}
//        try {
//            a.wait();
//        } catch (InterruptedException e) {
//            // TODO 自動生成された catch ブロック
//            e.printStackTrace();
//        }

        PrivateStaticTest b = new PrivateStaticTest();
        Test2 test2 = b.new Test2();
        Thread t2 = new Thread(test2);
        t2.start();

    }

    class Test1 implements Runnable{
        public void run() {
            for (int i = 0; i<10; i++){
                StringType a1 = new StringType("h1h");
                //StringType a2 = new StringType("h2h");
            }
        }
    }

    class Test2 implements Runnable{
        public void run() {
            for (int i = 0; i<10; i++){
                StringType a1 = new StringType("m1m");
                //StringType a2 = new StringType("m2m");
            }
        }
    }

}

测试结果
http://hiyachen.blog.chinaunix.net
id=1  word=h1h
id=2  word=h1h
id=3  word=h1h
id=4  word=h1h
id=5  word=h1h
id=6  word=h1h
id=7  word=h1h
id=8  word=h1h
id=9  word=h1h
id=10  word=h1h
id=11  word=m1m
id=12  word=m1m
id=13  word=m1m
id=14  word=m1m
id=15  word=m1m
id=16  word=m1m
id=17  word=m1m
id=18  word=m1m
id=19  word=m1m
id=20  word=m1m


阅读(8430) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~