进程和线程
进程是指一种正在运行的程序,有自己的地址空间。
特点:动态性、并发性、独立性、并发和并行
(并发是指多个cpu同时执行多个任务,并行是一个cpu采用时间分片同时执行多个任务)
线程是进程的一个执行单位,他是程序中一个单一的顺序控制流程,又称为轻量级进程,如果进程同时运行多个线程来同时完成不同的工作,则称为多线程。
特点:轻量级进程、独立调度的基本单位、可并发执行、共享进程资源
线程的三种创建方法
1、继承Thread类实现run方法
public class TestThread {
public static void main(String[] args) {
Test test = new Test();
test.start();
for (int i = 0; i <500 ; i++) {
System.out.println("main线程--->"+i);
}
}
}
class Test extends Thread{
//线程方法
public void run(){
for (int i = 0; i <500 ; i++) {
System.out.println("Thread线程--->"+i);
}
}
}
2、实现Runnable重写run方法
public class TestRunnable {
public static void main(String[] args) {
TestRun testRun = new TestRun();
new Thread(testRun).start();
for (int i = 0; i <500 ; i++) {
System.out.println("main线程--->"+i);
}
}
}
class TestRun implements Runnable{
@Override
public void run() {
for (int i = 0; i <500 ; i++) {
System.out.println("Runnable线程--->"+i);
}
}
}
3、实现callable接口实现call方法
public class Call {
public static void main(String[] args) throws InterruptedException, ExecutionException {
//创建线程
ExecutorService service = Executors.newFixedThreadPool(2);
TestCall tortoies = new TestCall("乌龟", 500);
TestCall rabbit = new TestCall("兔子", 1000);
//获取值
Future<Integer> result1 = service.submit(tortoies);
Future<Integer> result2 = service.submit(rabbit);
Thread.sleep(2000);
tortoies.setFlag(false);
rabbit.setFlag(false);
Integer num1 = result1.get();
Integer num2 = result2.get();
System.out.println("乌龟跑了--->"+num1+"步");
System.out.println("兔子跑了--->"+num2+"步");
//停止服务
service.shutdownNow();
}
}
class TestCall implements Callable<Integer>{
private String name ; //名称
private long time; //延时时间
private boolean flag =true;
private int step =0; //步
@Override
public Integer call() throws Exception {
while (flag){
Thread.sleep(time);
step++;
}
return step;
}
public TestCall(){
}
public TestCall(String name,long time){
this.name=name;
this.time=time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
}