南开小巷

导航

java 多线程

1.题目要求:自定义一个线程,创建三个实例,功能是打印1~100的数字。
其中,数字1+3*n(n>=0)必须是第一个线程实例打印的,2+3*n必须是第二个实例打印,3+3*n必须是第三个线程打印,打印结果严格递增,实例1,2,3依次轮流打印。

2.代码:

public class Printer implements Runnable {
    int i = 1;
 
    public void run() {
        try {
            synchronized (this) {
                while (i <= 100) {
                    String threadNo = Thread.currentThread().getName();
                    while (i % 3 != Integer.valueOf(threadNo) % 3) {
                        this.wait();
                    }
                    if (i <= 100)
                        System.out.println(threadNo + ": " + i++);
                    this.notifyAll();
                }
            }
        } catch (InterruptedException e) {
            System.out.println("InterruptedException occur");
        }
    }
}



public class Start {
     
    public static void main(String[] args) {
        Printer printer = new Printer();
        Thread t1 = new Thread(printer,"1");
        Thread t2 = new Thread(printer,"2");
        Thread t3 = new Thread(printer,"3");
        t1.start();
        t2.start();
        t3.start();
    }
}

代码2:

来个简单粗暴无同步的代码

package cn.byr.nuanyangyang.jishuqi;
 
class PrintingContext {
    public volatile int current = 1;
}
 
class Printer implements Runnable {
    private PrintingContext ctx;
    private String name;
    private int modulo;
 
    public Printer(PrintingContext ctx, String name, int modulo) {
        this.ctx = ctx;
        this.name = name;
        this.modulo = modulo;
    }
 
    @Override
    public void run() {
        while (true) {
            int cur = ctx.current;
            if (cur > 100) {
                break;
            }
 
            if (cur % 3 == modulo) {
                System.out.format("[%s] %d\n", name, cur);
                int newNum = cur + 1;
                ctx.current = newNum;
            }
        }
    }
}
 
public class MangDengDaiJiShuQi {
    public static void main(String[] args) throws Exception {
        PrintingContext ctx = new PrintingContext();
 
        Printer p1 = new Printer(ctx, "Printer 1", 1);
        Printer p2 = new Printer(ctx, "Printer 2", 2);
        Printer p3 = new Printer(ctx, "Printer 3", 0);
 
        Thread t1 = new Thread(p1);
        Thread t2 = new Thread(p2);
        Thread t3 = new Thread(p3);
 
        long timeStamp1 = System.currentTimeMillis();
        t1.start();
        t2.start();
        t3.start();
 
        t1.join();
        t2.join();
        t3.join();
        long timeStamp2 = System.currentTimeMillis();
 
        System.out.format("Total time: %dms", timeStamp2 - timeStamp1);
    }
}

  

 
 

posted on 2016-05-13 10:22  南开小巷  阅读(204)  评论(0编辑  收藏  举报