目录
1 实验名称
Java Thread实验
2 实验目的
继续熟练掌握在eclipse中调试代码
掌握Java 多线程中的基本概念及使用方法
掌握在GUI中使用Thread的子类创建线程
3 实验源代码
Application.java:
public class Application {
public static void main(String[] args) {//默认主线程
//创建一个子线程对象
MyThread myThread = new MyThread();
//开启子线程类
myThread.start();
Thread thread = new Thread(new MyThreadTarget());
thread.start();
//开启新线程
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
Thread.sleep(1000);
System.out.println("lll音乐播放·~~");
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}).start();
int i = 0; // ^---^
try { //表情 /'-=-'\
while (true) {
i++;
System.out.println("主线程:" + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
MyThread.java:
class MyThread extends Thread {
public void run(){
int i=0;
try {
while(true) {
i++;
System.out.println("子线程a:" + i);
Thread.sleep(500);
}
}catch(InterruptedException e) {
throw new RuntimeException(e);
}
}
}
MyThreadTarget.java:
class MyThreadTarget extends Thread {
public void run(){
int i=0;
try {
while(true) {
i++;
System.out.println("子线程b:" + i);
Thread.sleep(500);
}
}catch(InterruptedException e) {
throw new RuntimeException(e);
}
}
}
4 实验运行结果图
5 总结
线程是比进程更小的执行单位。一个进程在其执行过程中,可以产生多个线程,形成多条执行线索,每条线索,即每个线程也有它自身的产生、存在和消亡的过程,也是一个动态的概念。当Java程序包含图形用户界面(GUI)时,java虚拟机在运行应用程序时自动启动更多的线程。用Thread子类创建线程的优点是:可以在子类中增加新的成员变量,使线程具有某种属性,也可以在子类中新增加方法,使线程具有某种功能,但是java不支持多继承,Thread类的子类不能再扩展其他的类。注意的是,在编写Thread类的子类时需要重写父类的run方法,其目的是规定线程的具体操作,否则线程就什么也不做,因为父类的run方法中没有任何操作语句。