一、Thread类实现多线程
定义线程类
class MyThread extends Thread{
private String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
for(int i = 0 ; i < 50 ; i++) {
System.out.println(this.name + "正在工作中……" + i);
}
}
}
多线程启动
public class testThread {
public static void main(String[] args) {
// 实例化线程对象
MyThread mt1 = new MyThread("线程一");
MyThread mt2 = new MyThread("线程二");
MyThread mt3 = new MyThread("线程三");
// 启动实例线程对象
mt1.start();
mt2.start();
mt3.start();
}
}
二、Runnable接口实现多线程
定义线程类`
public class MyThread implements Runnable{
private String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
for(int i = 0 ; i<50 ;i++) {
System.out.println(this.name + " 正在执行中……" + i);
}
}
}
多线程启动
public class testThread {
public static void main(String[] args) {
// 实例化继承Runnable接口的MyThread类
Runnable mt1 = new MyThread("线程一");
Runnable mt2 = new MyThread("线程二");
Runnable mt3 = new MyThread("线程三");
// 多线程启动
new Thread(mt1).start();
new Thread(mt2).start();
new Thread(mt3).start();
}
}
例题:已知某学校有n名教师,学校有m名学生,学校搞学生民意调查,每一位学生为每一位老师都打分,学生所打的所有的分数都集中到一个数组中。数据存放规律是,前m个数据是对1号老师的打分,接下来m个数据是对2号老师的打分,以此类推。请设计一个多线程的算法,计算出每一位老师的总打分。
输入格式:
第一行输入教师数,第二行输入学生数,第三行输入所有n*m个打分(整型),各个分数之间以一个空格分隔
输出格式:
按照教师原来的顺序,每行输出每一位老师的得分
输入样例:
在这里给出一组输入。例如:
2
3
1 2 3 4 5 6
输出样例:
在这里给出相应的输出。例如:
6
15
在这里插入代码片
```import java.util.*;
public class Main{
public static void main(String args[]) {
Scanner in=new Scanner(System.in);
int te;
int stu;
te=in.nextInt();
stu=in.nextInt();
//多线程启动,new多线程,但这里是一个数组,有老师个数这么多的数组
teacher tea[]=new teacher[te];
//有老师个数这么多的数组
for(int i=0;i<te;i++)
{
//将学生个数传入类中
tea[i]=new teacher(stu);
for(int j=0;j<stu;j++)
{
//输入每个学生的打分
int score=in.nextInt();
tea[i].countscore(score);
}
}
//老师个数个线程启动
for(int i=0;i<te;i++)
{
tea[i].start();
System.out.println(tea[i].getscore());
}
}
}
class teacher extends Thread
{
int score;
int stunum;
public teacher(int stunum)
{
this.stunum=stunum;
}
public void countscore(int score)
{
this.score+=score;
}
public int getscore()
{
return this.score;
}
}