创建线程的多种方式
创建线程的多种方式
继承Thread类
package com.thread.t1;public class Demo1 extends Thread{@Overridepublic void run() {while(!interrupted()) {System.out.println(getName()+"线程执行...");try {Thread.sleep(200);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }}public static void main(String[] args) {Demo1 d1 = new Demo1();Demo1 d2 = new Demo1();d1.start();d2.start();d1.interrupt();}
}
由于java的单根继承性 所以 不推荐使用继承的这种方式
interrupt() 停止线程,调用该方法会改变interrupted 的值
interrupted 线程的停止状态
实现Runnable接口
package com.thread.t1;public class Demo2 implements Runnable {@Overridepublic void run() {// TODO Auto-generated method stubwhile(true) {System.out.println("Thread Running ......");}}public static void main(String[] args) {Thread thread = new Thread(new Demo2());thread.run();}}
实现Runnable这种方式,是创建一个线程任务,而不是一个线程
因此需要把这个线程任务塞到线程类中,然后调用线程的start()方法
匿名内部类的方式创建线程
package com.thread.t1;/*** 匿名内部类的方式创建线程* @author Administrator**/
public class Demo3 {public static void main(String[] args) {//重写new Thread() {public void run() {System.out.println("thread running ...");};}.start();//线程任务new Thread(new Runnable() {@Overridepublic void run() {System.out.println("thread running..."); }}).start();//打印的是sub 因为子类覆盖了父类的run方法 也就是java中的多态new Thread(new Runnable() {@Overridepublic void run() {System.out.println("runnable");}}) {public void run() {System.out.println("sub");}; }.start();}
}
带返回值的线程
package com.thread.t1;import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;/*** 带返回值的线程* @author Administrator**/
public class Demo4 implements Callable {//类似于run方法@Overridepublic Integer call() throws Exception {System.out.println("call方法执行");Thread.sleep(2000);return 1;}public static void main(String[] args) throws InterruptedException, ExecutionException {Demo4 d = new Demo4();//对其封装FutureTask task = new FutureTask<>(d);Thread thread = new Thread(task);//执行线程 thread.start();//获取线程执行结果Integer result = task.get();System.out.println("线程执行的结果为:"+result);}}
定时器
package com.thread.t1;import java.util.Timer;
import java.util.TimerTask;/*** 定时器 * 某一个时间点执行某件事* @author Administrator**/
public class Demo5 {public static void main(String[] args) {Timer timer = new Timer();//立刻执行 每1秒执行一次timer.schedule(new TimerTask() {@Overridepublic void run() {//在run方法中实现定时任务System.out.println("timerTask running...");}}, 0, 1000);}
}
简单介绍, Timer 不可控
线程池
package com.thread.t1;import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;/*** 线程池* * @author Administrator**/public class Demo6 {public static void main(String[] args) {// 固定容量的线程池
// ExecutorService threadPool = Executors.newFixedThreadPool(10);//不够用就创建 够用就回收ExecutorService threadPool = Executors.newCachedThreadPool();for (int i = 0; i < 100; i++) {threadPool.execute(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubSystem.out.println(Thread.currentThread().getName());}});}//停掉线程池threadPool.shutdown();}
}
lambda 表达式
package com.thread.t1;import java.util.Arrays;
import java.util.List;/*** lambda 表达式* @author Administrator**/
public class Demo7 {public int add(List values) {return values.parallelStream().mapToInt(a -> a).sum();}public static void main(String[] args) {List values = Arrays.asList(10,20,30,40,50);int res = new Demo7().add(values);System.out.println("计算的结果为:"+res);}
}
spring方式实现
这里用注解的方式
配置类 同时扫描包
package com.cheny.thread.t1;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
/*** java配置* @author Administrator**/
@Configuration
@ComponentScan("com.cheny.thread.t1")
@EnableAsync
public class Config {}
DemoService
package com.cheny.thread.t1;import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/*** 交给Spring容器去管理* @author Administrator**/
@Service
public class DemoService {//异步 的@Asyncpublic void a() {while(true) {System.out.println("a");try {Thread.sleep(2000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}@Asyncpublic void b() {while(true) {System.out.println("b");try {Thread.sleep(2000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
}
启动方法
package com.cheny.thread.t1;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {public static void main(String[] args) {AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Config.class);DemoService d = ac.getBean(DemoService.class);d.a();d.b();}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
