创建线程的方法
1、Thread
思路:
1、创建一个类去继承thread接口,并重写run()方法。
2、在测试类中创建线程对象,调用方法start()开启线程。
示例代码:
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
}
public class TestOfMyThread {
public static void main(String[] args) {
// 测试线程
System.out.println(Thread.currentThread().getName());
MyThread myThread= new MyThread();
myThread.start();
for(int i = 0;i<=100;i++) {
System.out.println("---->"+Thread.currentThread().getName() + " : "+i);
}
System.out.println("程序运行结束!");
}
}
2、Runnable
思路:
1、创建一个类去实现Runnable接口,重写run() 方法。
2、在测试类中创建Runnable对象,并创建线程对象,调用start() 方法开启线程。
示例代码:
public class RunnableImpl implements Runnable {
@Override
public void run() {
for(int i = 0;i<=10;i++) {
System.out.println("------->"+Thread.currentThread().getName()+" : "+i);
}
}
}
public class TestOfRunnable {
public static void main(String[] args) {
System.out.println("这是创建线程的第二种方法!");
RunnableImpl impl= new RunnableImpl();
Thread thread = new Thread(impl);
thread.start();
for(int i = 0;i<=10;i++) {
System.out.println("------->"+Thread.currentThread().getName()+" : "+i);
}
}
}
3、Callable
思路:
1、创建一个类去实现Callable接口,实现call()方法。
2、在测试类中创建实现接口Callable的对象
3、创建FutrueTask对象并传入2的对象
4、创建线程对象,传入3的对象
5、调用start()方法。
注意:
run()方法是没有返回值,call方法能够返回一个值。
示例代码:
import java.util.concurrent.Callable;
public class CallableImpl implements Callable<Object> {
@Override
public Object call() throws Exception {
int result = 0;
for (int i = 0; i <= 100; i++) {
result = result + i;
}
return result;
}
}
import java.util.concurrent.FutureTask;
public class TestOfCallable {
public static void main(String[] args) throws Exception, Exception {
CallableImpl callableImpl = new CallableImpl();
FutureTask<Object> futureTask = new FutureTask<>(callableImpl);
Thread thread = new Thread(futureTask);
thread.start();
Object string = futureTask.get();
System.out.println(string);
//System.out.println(thread.getName());
}
}