Java开启线程的四种方法案例详解
1、继承Thread类
1.1 代码实现
package com.zyz.mynative.demo03;
public class ExtendThread extends Thread {
public static void main(String[] args) {
ExtendThread thread = new ExtendThread();
thread.start();
}
@Override
public void run() {
doSomething();
}
public void doSomething() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "执行" + i);
}
}
}
1.2 测试结果
2、实现Runnable接口
2.1 方式一:直接实现Runnable接口
避免单继承的局限性,方便共享资源,推荐使用
2.1.1 代码实现
package com.zyz.mynative.demo03;
public class RunnableImpl implements Runnable {
public static void main(String[] args) {
RunnableImpl runnable = new RunnableImpl();
Thread thread = new Thread(runnable);
thread.start();
}
@Override
public void run() {
doSomething();
}
private void doSomething(){
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "执行" + i);
}
}
}
2.1.2 测试结果
2.2 方式二:匿名内部类
2.2.1 代码实现
package com.zyz.mynative.demo03;
public class RunnableImpl2 {
public static void main(String[] args) {
RunnableImpl2 test = new RunnableImpl2();
test.myRun();
}
public void myRun(){
new Thread(new Runnable() {
@Override
public void run() {
doSomething();
}
}).start();
}
private void doSomething(){
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "执行" + i);
}
}
}
2.2.2 测试结果
3、实现Callable接口
3.1 代码实现
package com.zyz.mynative.demo03;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableImpl implements Callable<String> {
public static void main(String[] args) {
Callable<String> tc = new CallableImpl();
FutureTask<String> task = new FutureTask<>(tc);
new Thread(task).start();
try {
System.out.println(task.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
private int ticket = 5;
@Override
public String call() throws Exception {
for (int i = 0; i < 10; i++) {
System.out.println(doSomething());
}
return "出票任务完成";
}
public String doSomething() {
String result = "";
if (this.ticket > 0) {
result = "出票成功,ticket=" + this.ticket--;
} else {
result = "出票失败,ticket=" + this.ticket;
}
return result;
}
}
3.2 测试结果
4、创建线程池
4.1 代码实例
package com.zyz.mynative.demo03;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPool implements Runnable {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
ThreadPool threadPool = new ThreadPool("AA");
ThreadPool threadPoo2 = new ThreadPool("BB");
pool.execute(threadPool);
pool.execute(threadPoo2);
pool.shutdown();
}
String name;
public ThreadPool(String name) {
this.name = name;
}
@Override
public void run() {
doSomething();
}
private void doSomething() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "执行" + i + ",name=" + this.name);
}
}
}
4.2 测试结果
资料参考:创建线程池的实现方法
到此这篇关于Java开启线程的四种方法的文章就介绍到这了,更多相关java开启线程内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关文章