多线程

多线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* @author zss
*/

public class Test {
public static void main(String[] args) {
Cat cat = new Cat();
Dog dog =new Dog();
//不可调用
//cat.run();
Thread thread = new Thread(cat);
Thread thread1=new Thread(dog);
thread.start();
thread1.start();
}
}


/**当一个类继承了Thread类,该类就可以当作线程使用,run方法来源于Runnable接口*/
class Cat implements Runnable{
@Override
public void run() {
int j=0;
while (true){
System.out.println("喵喵");
try{
Thread.sleep(1000);}
catch(InterruptedException e){
System.out.println("喵喵出问题");
e.printStackTrace();
}
j++;
if (j==5){
break;
}
}

}
}
class Dog implements Runnable{
@Override
public void run(){
int i=0;
while (true) {
System.out.println("汪汪");
try{
Thread.sleep(1000);
}catch (InterruptedException e){
System.out.println("汪汪出问题");
e.printStackTrace();
}
i++;
if (i>=5){
break;
}
}
}
}

image-20220317113800843

上述中一个主线程和两个子线程,主线程执行优先执行完毕,但是子线程还没由结束,主线程会提结束,而子线程继续执行。