我们在使用电脑或者手机时都能够真切的感受到程序不一定都是单纯的单线程直行,而是会分叉,比如我们在用手机上网的时候,依旧还是能够听歌,这就是多进程,在程序中体现为多线程(Thread),而线程都是通过cpu这个大脑来进行调度的,定义一个线程必须继承Thread或者实现 Runnable接口,而后我们在主程序通过调用Thread中的静态方法start()等候执行,当线程一完成一步骤时,即开始运行同优先级的该线程,如下面例子:
public class TakeCourse {
public static void main(String[] args) {
TakeCourse take = new TakeCourse();
take.CourseSystem();
new Thread(new Runnable() {
int time = 0;
public void run() {
for (int i = 1;; i++) {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
time += i;
System.out.println("欧巴您已持续操作" + time + "分钟,请注意休息哦!");
}
}
}).start();
take.selectCourseSystem();
}
public static void main(String[] args) {
TakeCourse take = new TakeCourse();
take.CourseSystem();
new Thread(new Runnable() {
int time = 0;
public void run() {
for (int i = 1;; i++) {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
time += i;
System.out.println("欧巴您已持续操作" + time + "分钟,请注意休息哦!");
}
}
}).start();
take.selectCourseSystem();
}
public void selectCourseSystem() {
System.out.println("======= 欢迎进入学生选课系统! ====== ");
}
public void CourseSystem() {
System.out.println("======= 欢迎进入学生选课系统! ====== ");
}
public void CourseSystem() {
System.out.println("开始线程1 ");
}