您的位置:首页 > 编程语言 > Java开发

java并发

2016-07-06 19:16 267 查看
三个线程打印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();
}
}结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 线程 并发 同步