一、实现多线程的三种方式:
继承Thread类、实现Runnable接口(重点)、实现Callable接口
1、继承Thread
public class TestThread extends Thread{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("学习中。。。"+i);
}
}
public static void main(String[] args) {
//main线程
//创建一个线程对象
TestThread testThread = new TestThread();
//调用start方法开启线程
testThread.start();
for (int i = 0; i < 20; i++) {
System.out.println("main线程。。。"+i);
}
}
}
2、实现Runnable接口
public class TestRunnable implements Runnable{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("学习中。。。"+i);
}
}
public static void main(String[] args) {
//main线程
//创建Runnable接口的实现类对象
TestRunnable testRunnable = new TestRunnable();
//创建线程对象,开启线程
new Thread(testRunnable).start();
for (int i = 0; i < 20; i++) {
System.out.println("main线程。。。"+i);
}
}
}
3、实现Callable接口
public class TestCallable {
public static void main(String[] args) throws Exception {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(5);
for (int i = 0; i < 5; i++) {
Future<Integer> result = pool.schedule(new Callable<Integer>(){
@Override
public Integer call() throws Exception {
int num = new Random().nextInt(100);//生成随机数
System.out.println(Thread.currentThread().getName() + " : " + num);
return num;
}
}, 1, TimeUnit.SECONDS);
System.out.println(result.get());
}
pool.shutdown();
}
}

2446

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



