疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

Java两个线程一个打印奇数一个打印偶数


 

   

  设计两个线程类,一个线程类负责打印100以内所有的偶数,另一个线程打印100以内所有的奇数。要求偶数线程每打印10个偶数以后,就让奇数线程打印10个奇数,如此交替进行。

  public class TwoThreadPrint {

  public static void main(String[] args) {

  PrintBean bean = new PrintBean();

  for (int i = 0; i < 2; i++) {

  new Thread(new PrintTask(bean, "Thread" + String.valueOf(i+1) + ":")).start();

  }

  }

  }

  class PrintBean{

  private int count = 0;

  public int getCount(){

  return count;

  }

  public void nextCount(){

  count += 1;

  }

  public void setCount(int count){

  this.count = count;

  }

  public boolean isNotCompleted(){

  return count < 5;

  }

  boolean evenTurn = true;

  }

  class PrintTask implements Runnable{

  PrintBean two;

  String name;

  public PrintTask(PrintBean two, String name){

  this.two = two;

  this.name = name;

  }

  public void run() {

  while (two.isNotCompleted()) {

  synchronized (two) {

  printNum(two.getCount());

  }

  }

  }

  public void printNum(int startNum) {

  if (two.evenTurn) {

  for (int i = 20 * startNum; i < 20 * startNum + 20; i += 2) {

  System.out.println(name + i);

  }

  two.evenTurn = false;

  two.setCount(two.getCount() - 1);

  } else {

  for (int i = 20 * startNum + 1; i < 20 * startNum + 20; i += 2) {

  System.out.println(name + i);

  two.evenTurn = true;

  }

  }

  two.nextCount();

  two.notifyAll();

  try {

  two.wait();

  } catch (InterruptedException e) {

  e.printStackTrace();

  }

  }

  }

  结果如下:

  Thread1:0

  Thread1:2

  Thread1:4

  Thread1:6

  Thread1:8

  Thread1:10

  Thread1:12

  Thread1:14

  Thread1:16

  Thread1:18

  Thread2:1

  Thread2:3

  Thread2:5

  Thread2:7

  Thread2:9

  Thread2:11

  Thread2:13

  Thread2:15

  Thread2:17

  Thread2:19

  Thread1:20

  Thread1:22

  Thread1:24

  Thread1:26

  Thread1:28

  Thread1:30

  Thread1:32

  Thread1:34

  Thread1:36

  Thread1:38

  Thread2:21

  Thread2:23

  Thread2:25

  Thread2:27

  Thread2:29

  Thread2:31

  Thread2:33

  Thread2:35

  Thread2:37

  Thread2:39

  Thread1:40

  Thread1:42

  Thread1:44

  Thread1:46

  Thread1:48

  Thread1:50

  Thread1:52

  Thread1:54

  Thread1:56

  Thread1:58

  Thread2:41

  Thread2:43

  Thread2:45

  Thread2:47

  Thread2:49

  Thread2:51

  Thread2:53

  Thread2:55

  Thread2:57

  Thread2:59

  Thread1:60

  Thread1:62

  Thread1:64

  Thread1:66

  Thread1:68

  Thread1:70

  Thread1:72

  Thread1:74

  Thread1:76

  Thread1:78

  Thread2:61

  Thread2:63

  Thread2:65

  Thread2:67

  Thread2:69

  Thread2:71

  Thread2:73

  Thread2:75

  Thread2:77

  Thread2:79

  Thread1:80

  Thread1:82

  Thread1:84

  Thread1:86

  Thread1:88

  Thread1:90

  Thread1:92

  Thread1:94

  Thread1:96

  Thread1:98

  Thread2:81

  Thread2:83

  Thread2:85

  Thread2:87

  Thread2:89

  Thread2:91

  Thread2:93

  Thread2:95

  Thread2:97

  Thread2:99