1、继承Thread类,重写run方法
public class MyThread extends Thread{
public void run(){
for(int i = 0;i<100;i++){
System.out.println(“”)
}
}
}
public class ThreadDemo(){
public static void main(String[] args){
MyThread mt1 = new MyThread();
MyThread mt2 - new MyThread();
mt1.setName(“线程1”);
mt2.setName(“线程2”);
mt1.start();
mt2.start();
}
}
2、实现Runnable接口,重写run方法
步骤:
1、创建MyRunnable类实现runnable接口
2、重写run方法
3、创建MyRunnable类的对象
4、创建Thread类的对象,并把MyRunnable类对象作为参数传递
public MyRunnable implements Runnable{
public void run(){
for(int i = 0;i<100;i++){
System.out.println(i);
}
}
}
public class MyRunnableDemo{
public static void main(String[] args){
MyRunnable my = new MyRunnable();
Thread t1 = new Thread(my,”线程1”);
Thread t2 = new Thread(my,”线程2”);
t1.start();
t2.start();
}
}
3、实现callable接口,重写call方法,可提供返回值
依赖于线程池使用
public class MyCallable implements Callable<Integer>{
private int number;
public MyCallable(int number){
this.number = number;
}
public Integer call() throws Exception{
int sum = 0;
for(int i=1;i<number;i++){
sum += i;
}
return sum;
}
}
//测试类
public class CallableDemo{
public static void main(String[] args) throws Exception{
Executorservice pool = Executors.newFixedThreadPool(2);
Future<Integer> f1 = pool.submit(new MyCallable(100));
Future<Integer> f1 =pool.submit(new Mycallable(50));
Integer i1 = f1.get();
Integer i2 = f2.get();
System.out.println("1-100的和是:" + i1);
System.out.println("1-50的和是:" + i2);
pool.shutdown;
}
}