1:继承Thread类
package cn.mld
//java中实现多线程的类,继承Thread类(java.lang.Thread)
public class MyThread extends Thread{
private String title;
public MyThread(String title) {
this.title=title;
}
@Override
public void run()//所有的线程从run方法中开始执行
{
for(int x=0;x<5;x++)
{
System.out.println(title+",x="+x);
}
}
}
2:实现Runnable接口
//实现Runnable接口,可以实现多个接口
public class MyRunnable implements Runnable{
private String title;
public MyRunnable(String title) {
this.title=title;
}
@Override
public void run()//所有的线程从run方法中开始执行
{
for(int x=0;x<5;x++)
{
System.out.println(title+",x="+x);
}
}
3:实现Callable接口
//JDK1.5之后引入了java.util.concurrent包,这个包主要是进行高性能的并发的包
//java.lang.concurrent.Callable这个类有返回值
public class MyCallable implements Callable<String>{
private String title;
public MyCallable(String title) {
this.title=title;
}
@Override
public String call() throws Exception {
for(int x=0;x<5;x++)
{
System.out.println(title+",x="+x);
}
return "current over!";
}
}
}
4:利用线程池创建
//创建线程池 java.util.concurrent.Executors:创建无限大小的线程
public class ThreadPoolDemo {
public static void main(String[] args) {
//创建一个线程池模型
ExecutorService newCachedThreadPool=Executors.newCachedThreadPool();
for( int x=0;x<10;x++)
{
int index=x;
newCachedThreadPool.submit(new Runnable() {
@Override
public void run() {
System.out.println("线程"+index);
}
});
}
System.out.println("------------------------");
for( int x=0;x<20;x++)
{
int index=x;
newCachedThreadPool.submit(new Thread());
System.out.println("线程"+index);
}
newCachedThreadPool.shutdown();//关闭线程池
}
}