程序:静态的一些数据,可执行的
进程:正在进行的程序,每个进程都单独占用一块内存,
多个进程之间不能数据共享,
必须通过网络交换数据
线程:一个进程内部的多个并行的运行单元,
同一个进程的多个线程之间可以通过内存共享数据
线程的格式;
如何定义线程
继承Thread
重写run()
线程要做的事情必须全部在run中调用执行
public class A extends Thread{
public void run(){
//线程要干的活...
}
}
如何启动线程:
线程对象.start();
start()方法只是给了虚拟机一个信号,本线程的run方法可以执行了
至于什么时候执行,由虚拟机根据具体的情况安排
public class A extends Thread{
public void run(){
线程需要做的事情
}
//主函数
A a = new A();
//线程的启动必须是用start,不能是run
a.start();
}
package Thread0627;
/**
* 多线程的创建 1.类继承Thread 2.线程做的事情写在run方法中
* 3,启动线程需要实例化的对象启动.start 4,线程传递参数只能
* 通过构造方法传递
*
* 启动线程使用的是start,实际上是告诉虚拟机线程已经准备好了可以
* 启动,然后再调用run
*/
import java.util.ArrayList;
import java.util.Iterator;
public class hello extends Thread{
ArrayList<String> list = new ArrayList<String>();
private String name;
public hello(String name){
this.name = name;
}
public void run(){
for(int i =0;i<5;i++){
System.out.println(name +"运行" + i);
// list.add("name"+i);
}
}
// //使用for遍历
// for(int i = 0;i<list.size();i++){
// String str=list.get(i);
// System.out.println(str);
// }
//使用迭代器进行遍历
//将元素添加到迭代器中,再进行遍历
// Iterator<String> iter = list.iterator() ;
// while(iter.hasNext()){
// String str=iter.next();
// System.out.println(str);
// }
//
// for(String str:list){
// System.out.println(str);
// }
// }
public static void main(String[] args) {
//主函数来启动线程
hello a = new hello("A");
hello b = new hello("B");
a.start();
b.start();
}
}
用start启动线程输出的结果:线程输出的顺序随机变化的
B运行0
B运行1
B运行2
B运行3
B运行4
A运行0
A运行1
A运行2
A运行3
A运行4
不能直接使用run 来启动线程:
a.run();
b.run();
输出的结果:
A运行0
A运行1
A运行2
A运行3
A运行4
B运行0
B运行1
B运行2
B运行3
B运行4
启动线程是main来启动的,启动线程的的对象在创建时 ,如果需要创建参数必须通过构造方法来传参数
使用线程来统计硬盘的文件个数:
package Thread0627;
public class Filecount extends Thread{
int i = 0;
String path;
//通过构造方法传递参数
public Filecount(String path){
this.path = path;
}
public void run(){
count();
}
public void count(){
//写一个死循环不断的进行统计
while(true){
i++;
System.out.println("正在统计"+path +"盘"+"有"+i+"个文件" );
try {
Thread.sleep(50);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package Thread0627;
public class threadDemo {
public static void main(String[] args) {
//主函数来启动线程,这个程序中有五个线程
//通过实例化来创建线程对象
Filecount f1 = new Filecount("C");
Filecount f2 = new Filecount("D");
Filecount f3 = new Filecount("E");
Filecount f4 = new Filecount("F");
f1.start();
f2.start();
f3.start();
f4.start();
}
}
输出(列出部分结果):
正在统计C盘有1个文件
正在统计D盘有1个文件
正在统计F盘有1个文件
正在统计E盘有1个文件
......
......