- Thread方式
- extends Thread,覆盖Thread run方法,new当前类start()调用(直接调用run方法,会被识别为普通方法)
//测试代码才写main,实际运用最好异步实体单独封装,业务中调用
public class TestCompare extends Thread {
int i = 0;
public void run(){
for(;i<100; i++){
System.out.println(getName()+" --- "+i);
}
}
public static void main(String[] args) {
for(int i=0; i< 100;i++){
System.out.println(Thread.currentThread().getName() + " :" +i);
if(i == 20){
System.out.println("此时主线程:"+ i);
new TestCompare().start();
new TestCompare().start();
}
}
}
}
- Runnable方式
- implements Runnable, 覆盖Runnable run方法,new Thread("new 当前类","线程名") start()调用
public class TestCompare implements Runnable{
int i = 0;
public void run(){
for(;i<100; i++){
System.out.println(Thread.currentThread().getName()+" --- "+i);
}
}
public static void main(String[] args) {
for(int i=0; i< 100;i++){
System.out.println(Thread.currentThread().getName() + " :" +i);
if(i == 20){
System.out.println("此时主线程:"+ i);
new Thread(new TestCompare(),"新线程1").start();
new Thread(new TestCompare(),"新线程2").start();
}
}
}
}
public class TestCompare implements Callable {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i < 101; i++) {
sum += i;
}
System.out.println(Thread.currentThread().getName() + " is running: " + sum);
return sum;
}
public static void main(String[] args) {
FutureTask<Integer> futureTask = new FutureTask<>(new TestCompare());
new Thread(futureTask).start();
try {
System.out.println("子线程的返回值: " + futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("这边呢");
}
}