多线程学习之多线程编程

来源:互联网 发布:2万钱网络大电影 编辑:程序博客网 时间:2024/05/29 12:39

有四个线程1、234。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD。初始都为空。现要让四个文件呈如下格式:

A1 2 3 4 1 2....

B2 3 4 1 2 3....

C3 4 1 2 3 4....

D4 1 2 3 4 1....

请设计程序。

import java.io.PrintWriter;//import java.util.concurrent.ExecutorService;//import java.util.concurrent.Executors;public class FourThreadFourFile {public static FILE file = new FILE();public static void main(String[] args) throws Exception {System.out.println("Hello World!");PrintWriter o = new PrintWriter("B");o.println("hello");o.close();// ExecutorService executors = Executors.newFixedThreadPool(5);// executors.execute(new PrintTask(1,"1"));// executors.execute(new PrintTask(2,"2"));// executors.execute(new PrintTask(3,"3"));// executors.execute(new PrintTask(4,"4"));// executors.shutdown();Thread th1 = new Thread(new PrintTask(1, "1"));Thread th2 = new Thread(new PrintTask(2, "2"));Thread th3 = new Thread(new PrintTask(3, "3"));Thread th4 = new Thread(new PrintTask(4, "4"));th1.start();th2.start();th3.start();th4.start();}public static class PrintTask implements Runnable {private int id = 0;public String name;public PrintTask(int id, String name) {this.id = id;this.name = name;}public void run() {while (true) {file.printFile(id, this);}}}}class FILE {// private static Lock = new ReentrantLock();// 代表需要打印的数private static int state = 0;// 选择操作文件// 0---A// 1---B// 2---C// 3---Dprivate static int select = 0;private static PrintWriter outA;private static PrintWriter outB;private static PrintWriter outC;private static PrintWriter outD;private static PrintWriter out;private static int num = 0;public FILE() {try {outA = new PrintWriter("C:/Users/admin/Desktop/A.txt");outB = new PrintWriter("C:/Users/admin/Desktop/B.txt");outC = new PrintWriter("C:/Users/admin/Desktop/C.txt");outD = new PrintWriter("C:/Users/admin/Desktop/D.txt");} catch (Exception fileNotFound) {}}public static synchronized void printFile(int id, FourThreadFourFile.PrintTask pt) {switch (select) {case 0:out = outA;print(id, pt);break;case 1:out = outB;// 调整idid = id - 1;if (id <= 0) {id += 4;}print(id, pt);break;case 2:out = outC;// 调整idid = id - 2;if (id <= 0) {id += 4;}print(id, pt);break;case 3:out = outD;id = id - 3;// 调整idif (id <= 0) {id += 4;}print(id, pt);break;}}public static synchronized void print(int id, FourThreadFourFile.PrintTask pt) {if (state == (id - 1)) {try {out.print(pt.name);System.out.println((char) ('A' + select) + "-----" + pt.name);Thread.sleep(10);} catch (InterruptedException ex1) {System.out.println("写入异常!!!");} finally {// 刷新缓冲区out.flush();}state++;if (state == 4) {out.println();state = 0;select++;if (select == 4) {select = 0;}}}}}



子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次,试写出代码


public class TestWait {private static Object object = new Object();      public static void main(String[] args) throws InterruptedException {          // TODO Auto-generated method stub          new Thread(new Runnable() {                            public void run() {                  // TODO Auto-generated method stub                  for (int i = 0; i < 50; i++) {                      synchronized (object) {                          for (int j = 0; j < 2; j++) {                              System.out.println("子循环在循环:ThreadCount == " + (j+1));                          }                          System.out.println("子循环执行了 --->"+(i+1)+"个2次");                          object.notify();                          try {                              object.wait();                          } catch (InterruptedException e) {                              // TODO Auto-generated catch block                              e.printStackTrace();                          }                                             }                  }              }          }).start();            for(int i = 0; i < 50; i++){              synchronized (object) {                  //主线程让出锁,等待子线程唤醒                  object.wait();                  for (int j = 0; j < 4; j++) {                      System.out.println("主循环在循环:MainCount == " + (j+1));                  }                  System.out.println("主循环执行了 --->"+(i+1)+"个4次");                                object.notify();                              }          }      }  }

启动三个线程,分别打印A、B、C,使得最终结果是ABCABCABCABCABCABCABCABCABCABC, 也就是循环打印ABC十次



public class ThreadABC implements Runnable{
private String name;
private Object prev;
private Object self;
// private static int count = 30;
public ThreadABC(String name, Object prev, Object self) {
super();
this.name = name;
this.prev = prev;
this.self = self;
}


@Override
public void run() {
// TODO Auto-generated method stub
int count = 10;
while(count>0){
synchronized (prev) {
synchronized (self) {
System.out.print(name);
count--;
self.notify();
}
try {
prev.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Object a = new Object();   
        Object b = new Object();   
        Object c = new Object();
Thread s1 = new Thread(new ThreadABC("A",c, a));
Thread s2 = new Thread(new ThreadABC("B",a, b));
Thread s3 = new Thread(new ThreadABC("C",b, c));
s1.start();
Thread.sleep(100);
s2.start();
Thread.sleep(100);
s3.start();
Thread.sleep(100);
}

}

0 0