实验十 Java多线程程序设计(一)
一、实验目的
- 掌握Java多线程程序设计方法。
二、实验内容
上机实现下列程序并观察程序的运行情况:
- 编写线程程序,在新线程中完成计算某个整数的阶乘。分别用Thread类和Runnable接口实现。
三、实验要求(必做实验,2学时)
- 掌握Java多线程的创建和使用。
- 掌握Java多线程同步技术;理解产生死锁现象的原因,学习如何避免死锁。
- 实验结果、发现和总结
Thread类:
/**
* @program: Chapter_12
* @description: The use of Thread
* @author: SXH
* @create: 2022-05-25 12:54
**/
public class Thread1 {
public static void main(String[] args) {
System.out.println("main thread start:");
FactorialThread thread=new FactorialThread(10);
thread.start();
System.out.println("main thread ends");
}
}
class FactorialThread extends Thread{
private int num;
public FactorialThread(int num) {
this.num = num;
}
public void run() {
int i = num;
int result = 1;
System.out.println("new thread start");
while(i>0) {
result = result * i;
i--;
System.out.println("The factorial of "+ num +" is "+ result);
System.out.println("new thread ends");
}
}
}
Runnable接口:
/**
* @program: Chapter_12
* @description: The use of Runnable
* @author: SXH
* @create: 2022-05-25 12:59
**/
public class Thread2 {
public static void main(String[] args) {
Runnable test=()->{
int a=1;
for (int i=1;i<=10;i++)
{
a*=i;
System.out.println("The factorial of 10 is "+a);
}
};
var t=new Thread(test);
t.start();
}
}