1.线程
- 线程被称为“轻量级进程”
- 每个线程对应一个独立的执行流
- 一个进程包含了多个线程,线程共享进程的资源
- 进程有独立性
- 线程如果出了问题,可能会影响进程。
- 创建线程的开销比创建进程小
- 进程是系统分配资源的最小单位,线程是系统调度的最小单位。一个进程内的线程之间是可以共享资源的。
2.进程和线程的区别
- 1.进程包含线程,一个进程可以包含一个进程,也可以包含多个线程
- 2.进程是资源分配的基本单位,线程是系统调度执行的基本单位。
- 3.进程和进程之间是相互独立的,同一个进程的若干线程之间,共享一些资源,如果某个线程出现异常,可能会导致整个进程终止,因此,其他线程也无法工作了。
3.新建线程
- 1.创建一个类,继承自Thread
- 2.重写run方法,写入线程要执行的代码
- 3.创建子类实例
- 4.调用子类Start方法
class MyThread extends Thread{
@Override
public void run() {
while (true){
System.out.println("这是新线程");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
System.out.println("hello world");
MyThread myThread=new MyThread();
myThread.start();
while(true){
System.out.println("这是主线程");
Thread.sleep(1000);
}
}
}
4.多线程
public class ThreadDemo1 {
private static long count = 100_0000_0000L;
public static void serial() {
long start = System.currentTimeMillis();
long a = 0;
for (long i = 0; i < count; i++) {
a++;
}
long b = 0;
for (long i = 0; i < count; i++) {
b++;
}
long end = System.currentTimeMillis();
System.out.println("执行时间" + (end - start));
}
public static void concurrency() throws InterruptedException {
long start=System.currentTimeMillis();
Thread t1=new Thread(){
@Override
public void run() {
long a=0;
for (long i = 0; i <count ; i++) {
a++;
}
}
};
t1.start();
Thread t2=new Thread(){
@Override
public void run() {
long b=0;
for (long i = 0; i <count ; i++) {
b++;
}
}
};
t2.start();
t1.join();
t2.join();
long end=System.currentTimeMillis();
System.out.println("执行时间"+(end-start));
}
public static void main(String[] args) throws InterruptedException {
concurrency();
}
}