java内部类线程_【JAVA】线程创建和匿名内部类

前言

看多线程时,发现一些匿名内部类的东西,然后就来总结一下。

1.继承Thread类

在类上实现匿名内部类

public classDemo1 {public static voidmain(String[] args) {

Thread t= newThread(){

@Overridepublic voidrun() {

System.out.println("This is the thread class");

}

};

t.start();

}

}

如果不用匿名内部类实现,则

public classDemo extends Thread {

@Overridepublic voidrun() {

System.out.println("This is Thread class");

}public static voidmain(String[] args) {

Demo demo= newDemo();

demo.start();

}

}

2.实现Runnable接口

在接口上实现匿名内部类

public classDemo2 {public static voidmain(String[] args) {

Runnable r= newRunnable() {public voidrun() {

System.out.println("this is Runnable interface");

}

};

Thread t= newThread(r);

t.start();

}

}

如果不用匿名内部类实现,则

public classDemo3 implements Runnable {public voidrun() {

System.out.println("This is Rubanle interface");

}public static voidmain(String[] args) {

Demo3 demo3= newDemo3();

Thread t= newThread(demo3);

t.start();

}

}

3.获取有返回值的线程

使用Callable接口和FutureTask

import java.util.concurrent.Callable;

import java.util.concurrent.FutureTask;public class Demo2 implements Callable{public static voidmain(String[] args) throws Exception{

Demo2 d= newDemo2();

FutureTask task = new FutureTask(d);

Thread t= newThread(task);

t.start();

System.out.println("我先干点别的。。。");

Integer result= task.get();

System.out.println("线程执行的结果为:" +result);

}publicInteger call() throws Exception {

System.out.println("正在进行紧张的计算");

Thread.sleep(3000);return 1;

}

}

4.线程定时任务

使用Timer类另起一个线程:

timer.schedule(TimerTask task, long delay, long period),第一个参数表示任务,第二个参数表示延迟时间,即启动main方法后多久才会调用run方法的时间;第三个参数表示每隔多久重复执行run()方法,用等差数列表示,delay表示首项, period表示公差。

import java.util.Timer;

import java.util.TimerTask;public classDemo1 {public static voidmain(String[] args) {

Timer timer= newTimer();

timer.schedule(newTimerTask() {

@Overridepublic voidrun() {

System.out.println("start to run");

}

},10000,1000);

System.out.println("main thread");

}

}

5.线程池

关于线程池的知识,暂不讲解,只是做个demo。

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;public classDemo2 {public static voidmain(String[] args) {

ExecutorService executorService=Executors.newCachedThreadPool();for(int i =0;i<=100;i++){

executorService.execute(newRunnable(){public voidrun() {

System.out.println(Thread.currentThread().getName() + "正在执行");

}

});

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值