创建线程的多种方式
继承Thread类
package com.thread.t1;
public class Demo1 extends Thread{
@Override
public void run() {
while(!interrupted()) {
System.out.println(getName()+"线程执行...");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.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 {
@Override
public void run() {
// TODO Auto-generated method stub
while(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() {
@Override
public void run() {
System.out.println("thread running...");
}
}).start();
//打印的是sub 因为子类覆盖了父类的run方法 也就是java中的多态
new Thread(new Runnable() {
@Override
public 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<Integer> {
//类似于run方法
@Override
public 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<Integer> 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() {
@Override
public 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() {
@Override
public void run() {
// TODO Auto-generated method stub
System.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<Integer> values) {
return values.parallelStream().mapToInt(a -> a).sum();
}
public static void main(String[] args) {
List<Integer> 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 {
//异步 的
@Async
public void a() {
while(true) {
System.out.println("a");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Async
public void b() {
while(true) {
System.out.println("b");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.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();
}
}