public class ThreadTest implements Runnable {
public static void main(String[] args) {
Runnable run = new ThreadTest();
Thread t1 = new Thread(run);
Thread t2 = new Thread(run);
t1.setName("Thread-01");
t2.setName("Thread-02");
t1.start();
t2.start();
}
private int i = 0;
public void run() {
while (i < 10) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (this) {
if (i >= 10) {
break;
}
i++;
System.out
.println(Thread.currentThread().getName() + ":i=" + i);
}
}
}
}
用synchronized (this)同步
最新推荐文章于 2018-11-07 10:27:12 发布
本文提供了一个Java多线程的示例代码,通过实现Runnable接口创建了两个线程,并使用synchronized关键字来同步共享资源的访问。每秒打印当前线程名及计数器值,直至计数器达到10。
1378

被折叠的 条评论
为什么被折叠?



