方法一:
/*
- 继承Thread类,重写run
*/
package com.fatiaoyu;
public class ThreadTest1 {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
thread1.setName(“线程1”);
MyThread thread2 = new MyThread();
thread2.setName("线程2");
thread1.start();
thread2.start();
}
}
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + ",i=" + i);
}
}
}
方法二:实现runnable接口,重写run方法
package com.fatiaoyu;
public class Runnable_test {
public static void main(String[] args) {
MyThread myThread1 = new MyThread();
Thread thread1 = new Thread(myThread1);
thread1.setName("线程1");
MyThread myThread2 = new MyThread();
Thread thread2 = new Thread(myThread2);
thread2.setName("线程2");
thread1.start();
thread2.start();
}
}
class MyThread2 implements Runnable {
public void run() {
for (int i = 1; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + “,i=” + i);
}
}
}
方法三:实现callable接口
package com.fatiaoyu;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Callable_test {
public static void main(String[] args) throws Exception {
MyThread3 mt = new MyThread3();
MyThread3 mt2 = new MyThread3();
FutureTask<String> task = new FutureTask<String>(mt);
FutureTask<String> task2 = new FutureTask<String>(mt2);
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task2);
thread1.start();
thread2.start();
System.out.println(task.get());
System.out.println(task2.get());
}
}
class MyThread3 implements Callable {
public String call() {
for (int i = 1; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + ",i=" + i);
}
return "执行成功";
}
}
打印结果: