一.多线程
(1)线程和进程
什么是线程?
线程指程序在执行过程中,能够执行程序代码的最小执行单元。
什么是进程?
程序在运行时在内存里开辟的空间。(正在运行的程序,不等于程序)
(2)怎么样实现多线程?
1.继承Thread类。
2.实现Runnable 接口
(3)实现多线程的意义
多线程的存在,其实是为了提高应用程序的使用率。
a.如果程序只有一条执行路径,那么该程序就是单线程程序
b.如果程序有多条执行路径,那么该程序就是多线程程序
(4)用代码来实现多线程
public class DuoXianChen {
public static void main(String[] args) {
int a = 0;
while(true) {
System.out.println(Thread.currentThread().getName()+"--"+a++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyThread extends Thread {
@Override
public void run() {
super.run();
int b = 0;
while(true) {
System.out.println(Thread.currentThread().getName()+"**"+b++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyThread1 implements Runnable{
@Override
public void run() {
int c = 0;
while(true) {
System.out.println(Thread.currentThread().getName()+"//"+c++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}