1:
/**
* Thread 实现多线程样例(可继承)
*/
public class ThreadImplementsTest implements Runnable{
public String params;
public ThreadImplementsTest(String params) {
this.params=params;
}
@Override
public void run() {
System.out.println(params);
}
public static void main(String[] args) {
for(int i=0;i<1000;i++) {
new Thread(new ThreadImplementsTest("测试"+i)).start();
}
}
}
2:
/**
* Thread 继承多线程样例
*/
public class ThreadExtendsTest extends Thread {
public String params;
public ThreadExtendsTest(String params) {
this.params=params;
}
@Override
public void run() {
System.out.println(params);
}
public static void main(String[] args) {
for(int i=0;i<1000;i++) {
new ThreadExtendsTest( "测试"+i ).start();
}
}
}
3:
public static int n=0;
private final static Object syncLock = new Object(); // 相当于线程锁,用于线程安全
public static void main(String[] args) {
for(int j=0;j<50;j++) {
new Thread(new Runnable() {
@Override
public void run() {
synchronized (syncLock){
for(int i=0;i<100;i++) {
++n;
System.out.println(n);
}
}
}
}).start();
}
}