1、实现Runnable接口
public class DemoThreadTask implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
DemoThreadTask task = new DemoThreadTask();
Thread t = new Thread(task);
t.start();
...
}
}
2、继承Thread类
public class DemoThread extends Thread{
@Override
//重写run方法
public void run() {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
DemoThread t = new DemoThread();
t.start();
...
}
}
3、实现Callable接口并通过FutureTask包装
public class DemoCallable implements Callable<String>{
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
return null;
}
public static void main(String[] args) throws Exception {
DemoCallable c = new DemoCallable();
FutureTask<String> future = new FutureTask<>(c);
Thread t = new Thread(future);
t.start();
...
String result = future.get(); //同步获取返回结果
System.out.println(result);
}
}
4、匿名内部类
public class Demo{
public static void main(String[] args) throws Exception {
//方式一:Thread匿名内部类
new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
}
}.start();
//方式二:Runnable匿名内部类
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
}
}).start();
...
}
}
5、Lambda表达式
public class Demo{
public static void main(String[] args) throws Exception {
new Thread(() -> System.out.println("running") ).start() ;
...
}
}
6、线程池
public class DemoThreadTask implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("running");
}
public static void main(String[] args) {
DemoThreadTask task = new DemoThreadTask();
ExecutorService ex = Executors.newCachedThreadPool();
ex.execute(task);
...
}
}
7、定时器
TimerTask的实现了Runnable接口,Timer内部有个TimerThread继承自Thread,因此绕回来还是Thread + Runnable。
public class DemoTimmerTask {
public static void main(String[] args) throws Exception {
Timer timer = new Timer();
timer.scheduleAtFixedRate((new TimerTask() {
@Override
public void run() {
System.out.println("定时任务1执行了....");
}
}), 2000, 1000);
}
}
版权属于:sunjianhua
本文链接:https://www.sunjianhua.cn/archives/java-thread.html
转载时须注明出处及本声明,如果不小心侵犯了您的权益,请联系邮箱:NTA2MTkzNjQ1QHFxLmNvbQ==
来看看 这个有点高级看不懂
最近上课讲到openmp用于多线程计算
那就学的不是一个语言