多线程-线程一打印1,2,3,4,5线程二打印6,7,8,9,10,线程三打印11,12,13,14,15,...直到45结束
多线程-线程一打印1,2,3,4,5线程二打印6,7,8,9,10,线程三打印11,12,13,14,15,...知道45结束
public class Exam3{
public static void main(String[]args){
MyThread t1=new MyThread("线程一");
MyThread t2=new MyThread("线程二");
MyThread t3=new MyThread("线程三");
t1.start();
t2.start();
t3.start();
}
}
class MyThread extends Thread{
static int num=1;
static Object key="key";
public MyThread(String name) {
super(name);
}
public void run() {
while(true) {
synchronized (key) {
if(num<=45)
for (int i = 0; i < 5; i++) {
System.out.println(getName()+":"+ num++);
}
else
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
ps:线程执行顺序可能不一样,线程的执行机会是cpu随机分配
控制台
线程一: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
2019-05-31-22:46:44