public class mThread extends Thread {
private String title;
public mThread(String title) {
super();
this.title = title;
}
@Override
public void run() {//重写run方法
// TODO Auto-generated method stub
for(int x = 0;x<10;x++) {
System.out.println(this.title+"运行,x="+x);
}
}
public class ThreadTest {
public static void main(String[] args) {
new mThread("线程A").start();
new mThread("线程B").start();
new mThread("线程C").start();
}
}
2.通过实现Runnable接口创建线程
package runnable.cn;
public class Test {
public static void main(String[] args) {
//创建线程对象
Thread thread1 = new Thread(new Mythread(),"线程A");
Thread thread2 = new Thread(new Mythread(),"线程B");
//启动线程
thread2.start();
thread1.start();
}
}
//使用实现Runnable接口的方式创建线程
class Mythread implements Runnable{
public void run(){//重写run方法
for(int i=1;i<=20;i++){
System.out.println(i+".你好,来自线程"+Thread.currentThread().getName());
}
}
}
3.通过实现Callable创建线程
package callable.cn;
import java.util.concurrent.Callable;
public class MyThread implements Callable<String> {
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
for (int i = 0; i < 100; i++) {
System.out.println( Thread.currentThread().getName()+"x="+i);
}
return "孙悟空";
}
}
package callable.cn;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Demo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask<String> task = new FutureTask<String>(new MyThread());
FutureTask<String> task1 = new FutureTask<String>(new MyThread());
Thread thread =new Thread(task);
Thread thread1 =new Thread(task1);
thread.start();
thread1.start();
System.out.println("[]"+task.get());
System.out.println("[]"+task1.get());
}
}
4.通过创建线程池创建线程
package com.cmy.threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolTest {
public static void main(String[] args) {
//尽量保证:任务数不要超过最大线程数+阻塞队列的长度
//(核心线程数,最大线程数,线程没有任务的存活时间,存活时间单位,阻塞队列,线程工场,线程拒绝策略)
ThreadPoolExecutor pool= new ThreadPoolExecutor(5, 10,
6, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(10),Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
for (int i = 0; i < 50; i++) {
pool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
pool.shutdown();
}
}