两个线程轮流打印数字,一直到100(多线程)

方法1:

package cn.hp.thread.homewoke; //1. 两个线程轮流打印数字,一直到100 public class Work1 implements Runnable{ static int num=0; static Boolean flag=true; static Object o=new Object(); @Override public void run() {synchronized (o){ while (num<100){ num++; if (true){ flag=false; System.out.println("t1:"+num); }else { flag=true; System.out.println("t2:"+num); } }} }public static void main(String[] args) {Thread t1 = new Thread(new Work1()); t1.start(); Thread t2 = new Thread(new Work1()); t2.start(); } }

方法2:
public class Work1{ static int num=101; static Work1 w=new Work1(); public static void main(String[] args) { //定义两个线程 Thread t1 = new Thread(new Thread1()); Thread t2 = new Thread(new Thread2()); t1.start(); t2.start(); }public static class Thread1 implements Runnable{@Override public void run() {while (true){ synchronized (w) {//synchronized()括弧内部是 同步锁对象 if (num>1){ try { w.notify(); //一次只能有一个线程拥有对象的监视器(就是绑定了一个监视器来判断是第几个线程) num--; System.out.println("t1:"+num); w.wait(); //重新获得对监视器的所有权后继续执行 } catch (InterruptedException e) { e.printStackTrace(); }}else{ System.exit(1); //当num=1退出系统 } } } } } public static class Thread2 implements Runnable{@Override public void run() { while (true){ synchronized (w) { if (num>1){ try { w.notify(); num--; System.out.println("t2:"+num); w.wait(); } catch (InterruptedException e) { e.printStackTrace(); }}else{ System.exit(1); } } } } } }

运行结果:
t1:100
t2:99
t1:98
t2:97
t1:96
t2:95
t1:94
t2:93
t1:92
t2:91
t1:90
t2:89
t1:88
t2:87
t1:86
t2:85
t1:84
t2:83
t1:82
t2:81
t1:80
t2:79
t1:78
t2:77
t1:76
t2:75
t1:74
t2:73
t1:72
t2:71
t1:70
t2:69
t1:68
t2:67
t1:66
t2:65
t1:64
t2:63
t1:62
t2:61
t1:60
t2:59
t1:58
t2:57
t1:56
t2:55
t1:54
t2:53
t1:52
t2:51
t1:50
t2:49
t1:48
t2:47
t1:46
t2:45
t1:44
t2:43
t1:42
t2:41
t1:40
t2:39
t1:38
t2:37
t1:36
t2:35
t1:34
t2:33
t1:32
t2:31
t1:30
t2:29
t1:28
t2:27
t1:26
t2:25
t1:24
t2:23
t1:22
t2:21
t1:20
t2:19
t1:18
t2:17
t1:16
t2:15
t1:14
t2:13
t1:12
t2:11
t1:10
t2:9
t1:8
t2:7
t1:6
t2:5
t1:4
t2:3
t1:2
t2:1
【两个线程轮流打印数字,一直到100(多线程)】Process finished with exit code 1

    推荐阅读