目录
1.线程与进程的关系
进程是资源分配的最小单位,线程是程序执行的最小单位
eg:人们打开迅雷软件就是一个进程,同时下载多部电影就是多个线程
2.创建线程的四种方式
2.1继承Thread
/**
* 继承方式实现线程
*/
public class ThreadDemo1 extends Thread{
@Override
public void run() {
System.out.println("线程被调用");
}
public static void main(String[] args) {
Thread t = new ThreadDemo1();
t.start();
}
}
2.2实现Runnable
/**
* 实现方式实现线程
*/
public class ThreadDemo1 implements Runnable{
public void run() {
System.out.println("线程被调用");
}
public static void main(String[] args) {
Thread t = new ThreadDemo1();
t.start();
}
}
2.3匿名内部类
/**
* 匿名内部类实现线程
*/
public class ThreadDemo1 {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
public void run() {
System.out.println("线程被调用了");
}
});
t.start();
}
}
2.4实现Callable
/**
* 并发包有返回值 实现线程
*/
public class ThreadDemo1 implements Callable {
public Object call() throws Exception {
System.out.println("这个是call()");
return "返回值";
}
public static void main(String[] args) throws Exception{
FutureTask task =new FutureTask(new ThreadDemo1());
Thread t =new Thread(task,"callable");
t.start();
System.out.println(task.get());
}
}