Java 线程学习总结(一) —— 创建线程的三种方式
方式一:继承Thread,重写run()方法
以两个同学分别报数为例:
/**
* 方法一
* 继承Thread 重写run()方法
* @author Sirm
*
*/
public class creat1{
public static void main(String[] args) {
XiaoMing xm = new XiaoMing();
XiaoHong xh = new XiaoHong();
xm.start();
xh.start();
}
}
/**
* 第一个线程
* @author Sirm
*
*/
class XiaoMing extends Thread{
@Override
public void run() {
for(int i=0;i<10;i++) {
System.out.println("XiaoMing报数:"+i);
}
}
}
/**
* 第二个线程
* @author Sirm
*
*/
class XiaoHong extends Thread{
@Override
public void run() {
for(int i=0;i<10;i++) {
System.out.println("XiaoHong报数:"+i);
}
}
}
方式二:实现Runnable接口,使用静态代理模式创建线程
- 避免单继承的局限性
- 方便资源共享,如购票系统
以两个同学抢报数为例
public class creat2 {
public static void main(String[] args) {
//创建真实角色,共享的资源
Number num = new Number();
//创建代理角色
Thread td1 = new Thread(num,"小明");
Thread td2 = new Thread(num,"小红");
//启动线程
td1.start();
td2.start();
}
}
/**
* 第一个线程
* @author Sirm
*
*/
class Number implements Runnable{
private int num = 100;
@Override
public void run() {
while(num >= 0) {
System.out.println(Thread.currentThread().getName()+"抢到"+num--);
}
}
}
方式三:实现Callable接口,利用ExecutorService和Future创建
- 有返回值
- 可以抛出异常
以两个同学在规定时间内报数为例
public class creat3 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
//创建两个线程
ExecutorService ser =Executors.newFixedThreadPool(2);
creat3_1 XiaoMing = new creat3_1("小明",100,1000);
creat3_1 XiaoHong = new creat3_1("小红",50,1000);
//获取值
Future<Integer> f1 = ser.submit(XiaoMing);
Future<Integer> f2 = ser.submit(XiaoHong);
System.out.println("小明在"+XiaoMing.getTime()+"ms内报了"+f1.get()+"个数");
System.out.println("小红在"+XiaoHong.getTime()+"ms内报了"+f2.get()+"个数");
}
}
class creat3_1 implements Callable<Integer>{
/*学生名*/
String name;
/*报数速度 speed ms报一个*/
long speed;
/*规定的时间*/
long time;
creat3_1(String n , long s , long t){
this.name = n;
this.speed = s;
this.time = t;
}
@Override
public Integer call() throws Exception {
int num = 0;
long end = System.currentTimeMillis()+time;
while(System.currentTimeMillis() < end) {
Thread.sleep(speed);
System.out.println(Thread.currentThread().getName()+"报数"+num++);
}
return num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public void setSpeed(long speed) {
this.speed = speed;
}
}