1.要达到的效果:
奇数线程: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
奇数线程:59
偶数线程:60
奇数线程:61
偶数线程:62
奇数线程:63
偶数线程:64
奇数线程:65
偶数线程:66
奇数线程:67
偶数线程:68
奇数线程:69
偶数线程:70
奇数线程:71
偶数线程:72
奇数线程:73
偶数线程:74
奇数线程:75
偶数线程:76
奇数线程:77
偶数线程:78
奇数线程:79
偶数线程:80
奇数线程:81
偶数线程:82
奇数线程:83
偶数线程:84
奇数线程:85
偶数线程:86
奇数线程:87
偶数线程:88
奇数线程:89
偶数线程:90
奇数线程:91
偶数线程:92
奇数线程:93
偶数线程:94
奇数线程:95
偶数线程:96
奇数线程:97
偶数线程:98
奇数线程:99
偶数线程:100
代码:
package thread;
public class printNumDemo {
static class Barrie{
int number = 1;
boolean isOdd = true;
public Barrie() {}
}
/**
* 打印奇数
* @author Administrator
*
*/
static class OddPrint implements Runnable{
Barrie barrie;
public OddPrint() {}
public OddPrint(Barrie barrie) {
super();
this.barrie = barrie;
}
@Override
public void run() {
synchronized(barrie) {
while(barrie.number <= 100) {
barrie.notify();
if(barrie.isOdd) {
System.out.println(Thread.currentThread().getName()+barrie.number);
barrie.number ++;
barrie.isOdd = false;
}else {
try {
barrie.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
/**
* 打印偶数
* @author Administrator
*
*/
static class EvenPrint implements Runnable{
Barrie barrie;
public EvenPrint() {}
public EvenPrint(Barrie barrie) {
super();
this.barrie = barrie;
}
@Override
public void run() {
synchronized(barrie) {
while(barrie.number <= 100) {
barrie.notify();
if(!barrie.isOdd) {
System.out.println(Thread.currentThread().getName()+barrie.number);
barrie.number ++;
barrie.isOdd = true;
}else {
try {
barrie.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args) {
Barrie barrie = new Barrie();
OddPrint oddPrint = new OddPrint(barrie);
EvenPrint evenPrint = new EvenPrint(barrie);
Thread t1 = new Thread(oddPrint);
t1.setName("奇数线程:");
Thread t2 = new Thread(evenPrint);
t2.setName("偶数线程:");
t1.start();
t2.start();
}
}