1继承Thread类的方式进行实现
//多线程的第一种启动方式
Thread t1 = new mythread();
Thread t2 = new mythread();
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
public class mythread extends Thread{
@Override
public void run() {
for (int i = 0;i < 100;i++){
System.out.println(getName() + "niubi");
}
}
2,实现Runnable接口的方式实现
public class mythread implements Runnable{
@Override
public void run() {
for (int i = 0;i < 100;i++){
Thread t = Thread.currentThread();
System.out.println(t.getName() + "niubi");
}
}
}
public static void main(String[] args) {
mythread m = new mythread();
Thread t1 = new Thread(m);
Thread t2 = new Thread(m);
t1.setName("3");
t2.setName("4");
t1.start();
t2.start();
}
3,利用Callable接口和Future接口(管理返回值)
public class mycallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i < 100; i++) {
sum = sum + i;
}
return sum;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
mycallable m = new mycallable();
FutureTask<Integer> f = new FutureTask<>(m);//管理多线程运行结果
Thread t = new Thread(f);
t.start();
Integer result = f.get();
System.out.println(result);
}

文章介绍了在Java中实现多线程的三种方式:1)继承Thread类并重写run方法;2)实现Runnable接口并将其传递给Thread;3)使用Callable接口和FutureTask来管理返回值。每种方式都包含示例代码,展示了如何创建和启动线程以及打印自定义信息或计算结果。
572

被折叠的 条评论
为什么被折叠?



