java并发

来源:互联网 发布:养老金的算法 编辑:程序博客网 时间:2024/05/20 05:08

三个线程打印1到100;

public class MyRunnable implements Runnable {    private int i =0;    @Override    public void run() {        while(i<100){            try {                Thread.sleep(100);            } catch (InterruptedException e) {                e.printStackTrace();            }            synchronized (this){//同步操作 锁住对象                if(i<100){                    System.out.println(Thread.currentThread().getName()+" "+ ++i);                }            }        }    }}public class ThreadQuesstion {    public static void main(String args[]){        MyRunnable run = new MyRunnable();        Thread a = new Thread(run,"a");        Thread b = new Thread(run,"b");        Thread c = new Thread(run,"c");        a.start();        b.start();        c.start();    }}
结果:


0 0
原创粉丝点击