java多线程学习

public class ThreadStaticInt extends Thread{
	private  int x = 0;
	public void run(){
		System.out.println(++x);
	}
}

 

 

public class TestThreadStaticInt {
	public static void main(String[] args) {
		for(int i = 0; i < 10; i++){
			Thread t = new ThreadStaticInt();
			t.start();
		}
	}
}

执行的结果是:输出10个1

 

如果把ThreadStaticInt类的x属性改为static,代码如下:

public class ThreadStaticInt extends Thread{
	private static 
int x = 0;
	public void run(){
		System.out.println(++x);
	}
}

 则输出:1,2,3,。。。,10

 

 

如果是用实现Runable接口的方法:

public class ThreadImplementRun implements Runnable{
	private int x = 0;
	public void run(){
		System.out.println(++x);
	}
}

 

public class TestThreadStaticInt {
	public static void main(String[] args) {
		ThreadImplementRun ti = new ThreadImplementRun();
		for(int i = 0; i < 10; i++){
			Thread t = new Thread(ti);
			t.start();
		}
	}
}

 

结果也是输出:1,2,3,。。。,10

 

 

 

 

 

你可能感兴趣的:(编程,多线程,Java,thread)