今天在此处再来保存点多线程的基本知识和本小伙的一个奇怪的代码。
多线程中子进程的代码中可以有两种方法一种是继承Thread类如下图所示
public class MyFirstThread extends Thread{
@Override
public void run() {
for (int i = 0; i <=100 ; i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
}
还有一种是连接Runable接口
public class MyFirstThread2 implements Runnable{
@Override
public void run() {
for (int i = 0; i <=100 ; i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
}
两种写法都是要重写所需要的方法,书写模式差不多。不同的是Runable使用的资源是共享的。打个比方Runable是一共10个苹果,十个苹果上写上一到十的数字,俩人从十个中拿苹果不会重复。
反之继承Thread是两堆苹果,每堆十个,上面写着1-10的数字,俩人分别拿两堆的苹果。俩人所拿苹果的编号都是1-10,编号是重复的。给个代码例子如下图
//继承Thread的情况
//写一个取票的进程
//写一个for循环对所取票的票号进行循环
public class TicketThread extends Thread {
private int ticket=10;
@Override
public void run() {
for (int i = 0; i <=10; i++) {
if (this.ticket>0){
System.out.println(Thread.currentThread().getName()+"买票--"+this.ticket--);
}
}
}
}
//创建俩窗口,进行多线程的售票
public static void main(String[] args) {
TicketThread window1 = new TicketThread();
window1.setName("一号窗口");
TicketThread window2 = new TicketThread();
window2.setName("二号窗口");
window1.start();
window2.start();
}
然后继承Tread的这种方式的弊端就体现出来了如图所示编号发生了重叠
然后让我们看看Runable的这种代码来了:
//跟上面想要做的一样都是写一个售票的循环
//子进程
public class MyFirstThread2 implements Runnable{
@Override
public void run() {
for (int i = 0; i <=100 ; i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
}
//同样定义俩窗口进行售票
public static void main(String[] args) {
TicketRunable window=new TicketRunable();
Thread window1 = new Thread(window, "window1");
Thread window2 = new Thread(window, "window2");
window1.start();
window2.start();
}
不同的结果
好了,两种写法的不同就先到这里。
接下来是本人自己初学的一个小实验:
输入两个运动员的名字,百米的速度,还有总的路程让这两个运动员比赛跑步,谁先到达,另一个也停止。
public class ClimbThread extends Thread{
private int time;
private int num=1;
private String name;
public ClimbThread(int time, int rela,String name) {
this.time = time*1000;
this.num = rela/100;
this.name=name;
}
@Override
public void run() {
int nums=1;
while (nums<=num){
try {
ClimbThread.sleep(time);
System.out.println(name+"跑完了"+(nums*100)+"米");
nums++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ClimbTest {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("设置第一个人的每一百米时长:");
int time=input.nextInt();
System.out.print("跑道长度:");
int line=input.nextInt();
System.out.println("输入该运动员的姓名:");
String name= input.next();
ClimbThread climbThread=new ClimbThread(time,line,name);
Thread thread=new Thread(climbThread,name);
System.out.print("设置第二个人的每一百米时长:");
int time1=input.nextInt();
System.out.println("输入该运动员的姓名:");
String name1= input.next();
ClimbThread climbThread1=new ClimbThread(time1,line,name1);
climbThread.start();
climbThread1.start();
// Boolean flag=climbThread.isAlive();
// Boolean flag1=climbThread1.isAlive();
// if (!flag&&flag1){
// climbThread1.interrupt();
// }else if (flag&&flag1){
// climbThread.interrupt();
// }else {
// System.out.println(" h" );
// }
}
}