Java多线程的在开发中用到的很多,简单总结一下几种写法,分别是继承Thread方法,实现Runnable接口,实现Callable接口;
1.继承Thread方法
class TestThread extends Thread{
String name;
public TestThread(String name){
this.name=name;
}
@Override
public void run() {
for (int i = 0; i < 6; i++) {
System.out.println(this.name+":"+i);
}
}
}
main方法调用:
Thread启动有两个方法,一个是start()方法,一个是run()方法,但是直接调用run方法时线程不会交替运行,而是顺序执行,只有用start方法时才会交替执行
TestThread tt1 = new TestThread("A");
TestThread tt2 = new TestThread("B");
tt1.start();
tt2.start();
运行结果:
2.实现Runnable接口,有多种写法
2.1外部类
class TestRunnable implements Runnable{
String name;
public TestRunnable(String name){
this.name=name;
}
@Override
public void run() {
for (int i = 0; i < 6; i++) {
System.out.println(this.name+":"+i);
}
}
}
调用:
TestRunnable tr1 = new TestRunnable("C");
TestRunnable tr2 = new TestRunnable("D");
new Thread(tr1).start();
new Thread(tr2).start();
2.2匿名内部类方式
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
}
}).start();
2.3 Lamda表达式,jdk1.8,只要是函数式接口,都可以使用Lamda表达式或者方法引用
new Thread(()->{
for (int i = 0; i < 6; i++) {
System.out.println(i);
}
}).start();
2.4ExecutorService创建线程池的方式
class TestExecutorService implements Runnable{
String name;
public TestExecutorService(String name){
this.name=name;
}
@Override
public void run() {
for (int i = 0; i < 6; i++) {
System.out.println(this.name+":"+i);
}
}
}
调用:可以创建固定个数的线程池
ExecutorService pool = Executors.newFixedThreadPool(2);
TestExecutorService tes1 = new TestExecutorService("E");
TestExecutorService tes2 = new TestExecutorService("F");
pool.execute(tes1);
pool.execute(tes2);
pool.shutdown();
运行结果跟2.1差不多
3.实现Callable接口,可以返回结果
//Callable<V>提供返回数据,根据需要返回不同类型
class TestCallable implements Callable<String>{
private int ticket = 5;
@Override
public String call() throws Exception {
for (int i = 0; i < 5; i++) {
if(this.ticket>0)
System.out.println("买票,ticket="+this.ticket--);
}
return "票卖完了";
}
}
调用:
Callable<String> tc = new TestCallable();
FutureTask<String> task = new FutureTask<String>(tc);
new Thread(task).start();
try {
System.out.println(task.get());//获取返回值
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
运行结果:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。