1.继承Thread类
public class Demo1 extends Thread{
public Demo1(String name) {
// TODO Auto-generated constructor stub
super(name);
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(getName()+"线程执行了");
}
public static void main(String[] args) {
Demo1 d1 = new Demo1("线程1");
Demo1 d2 = new Demo1("线程2");
// d1.setDaemon(true); 守护线程,当主线程结束时,守护线程也退出
d1.start();
d2.start();
}
}
2.继承Runnable接口
public class Demo2 implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.err.println(Thread.currentThread().getName());
}
}
public static void main(String[] args) {
Demo2 d1 = new Demo2();
Demo2 d2 = new Demo2();
Thread t1 = new Thread(d1);
Thread t2 = new Thread(d2);
t1.start();
t2.start();
}
}
3匿名内部类的方式
public class Demo3 {
public static void main(String[] args) {
// 匿名内部类创建的2种方式
/*new Thread(){
public void run() {
while (true) {
System.out.println("start");
}
};
}.start();*/
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("2start");
}
}).start();
}
}
4.带返回值的线程
public class Demo4 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
System.out.println("执行callable");
return 1;
}
/*
* 通过callable创建带返回值的方式
*/
public static void main(String[] args) {
Demo4 demo4 = new Demo4();
FutureTask<Integer> tasks = new FutureTask<Integer>(demo4);
Thread thread = new Thread(tasks);
thread.start();
try {
Integer integer = tasks.get();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
5.定时器
public class Demo5 {
public static void main(String[] args) {
// task执行的任务,firsttime开始时间,周期隔多久执行一次
Timer timer =new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("time task");
}
}, 0, 1000);
}
}
6.线程池
public static void main(String[] args) {
// 创建带有10个线程的线程池,使用的话线程池申情,不用则返回
// ExecutorService threadpool = Executors.newFixedThreadPool(10);
ExecutorService threadpool = Executors.newCachedThreadPool();
// 提交任务给线程池,提交100个线程任务,由10个线程执行
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();
}
网友评论