进程(Process)是指计算机中已运行的程序,是系统进行资源分配和调度的基本单位,是操作系统结构的基础。在早期面向进程设计的计算机结构中,进程是程序的基本执行实体;在当代面向线程设计的计算机结构中,进程是线程的容器。进程是程序真正运行的实例(如正在运行的QQ),若干进程可能与同一个程序相关,且每个进程皆可以同步或异步的方式独立运行。(搜狗百科)
线程(thread)是操作系统能够进行运算调度的最小单位,它被包涵在进程之中,是行程中的实际运作单位(如QQ中的语音功能)一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并行多个线程,每条线程并行执行不同的任务。在Unix SystemV及SunOS中也被称为轻量进程(lightweight processes),但轻量进程更多指内核线程(kernel thread),而把用户线程(user thread)称为线程。计算机科学术语,指运行中的程序的调度单位。(搜狗百科)
多线程是多个线程同时进行,或是由于两个或多个线程在进行切换时时间极短用户感觉不到。多线程不是提高了处理效率而是提高了使用效率。
Java多线程核心技术
一个进程至少有一个线程,调用public static viod main()方法线程,他是由JVM创建的
public class xian {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
}
}
输出结果:main
这个main与main方法没有关系只是名字相同,它是指一个main线程在执行main()代码
Thread.currentThread()获得当前线程
class MyThread extends Thread {
@Override
public void run() {
try {
Thread.sleep(500);
Thread t = Thread.currentThread();
System.out.println("当前线程名字:" + t.getName() + " 当前线程的优先级别为:"+ t.getPriority() + " ID:" + t.getId());
System.out.println("当前线程名字:" + this.getName() + " 当前线程的优先级别为:" + this.getPriority() + " ID:"+ this.getId());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class aa{
public static void main(String[] args) {
MyThread mt = new MyThread();
new Thread(mt, "Name1").start();
new Thread(mt, "Name2").start();
new Thread(mt).start();
System.out.println(Thread.currentThread().getName()); // main主方法
}
}
输出结果:
main
当前线程名字:Thread-1 当前线程的优先级别为:5 ID:15
当前线程名字:Name1 当前线程的优先级别为:5 ID:13
当前线程名字:Name2 当前线程的优先级别为:5 ID:14
当前线程名字:Thread-0 当前线程的优先级别为:5 ID:12
当前线程名字:Thread-0 当前线程的优先级别为:5 ID:12
当前线程名字:Thread-0 当前线程的优先级别为:5 ID:12
这个实说this和Thread.currentThread()关系,我也不太懂-_-
多线程编程方法
1:继承Thread类
2:实现Runnable接口
Thread类结构:
public class Thread implements Runnable
Thread类实现了Runnable,是多态的关系,由于Java是单一继承,所以Thread不能多个继承,但是可以边继承边实现
public class myThread extends Thread {
public void run (){
super.run();
System.out.println(“MyTread”);
}
}
pubic class Run(){
}
代码运行结果与代码执行或调用顺序无关。