Thread实现多线程:
public class Thread2 extends Thread{
public int i;
public void run(){
for(; i < 100 ;i++) {
System.out.println(getName() + " " + i);
}
}
public static void main(String[] args){
for (int j = 0; j < 100; j++) {
System.out.println(Thread.currentThread().getName() + " " + j);
if (j == 20) {
new Thread2().start();
new Thread2().start();
}
}
}
}
运行部分结果:
Thread-1 97
Thread-1 98
Thread-1 99
main 21
main 22
main 23
main 24
main 25
main 26
main 27
main 28
Thread-2 0
Thread-2 1
Thread-2 2
Thread-2 3
Thread-2 4
可以看出各个线程的属性不共享
//Runnable 实现多线程
public class Thread1 implements Runnable{
public int i;
public void run(){
for(; i < 100 ;i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
public static void main(String[] args){
for (int j = 0; j < 100; j++) {
System.out.println(Thread.currentThread().getName() + " " + j);
if (j == 20) {
//new Thread1().start();
Thread1 ss = new Thread1();
new Thread(ss,"新线程1").start();
new Thread(ss,"新线程2").start();
}
}
}
}
新线程1 45
新线程1 46
新线程1 47
新线程1 48
新线程2 49
新线程2 50
新线程2 51
新线程2 52
新线程2 53
新线程2 54
新线程2 55
新线程2 56
新线程2 57
可以看出属性是共享的