两线程交替打印数字
2015-11-04 14:55
232 查看
问题: 起两个线程,线程1打印奇数,线程2打印偶数,两线程交替打印。
解决方法: 通过wait(),notify()实现。
注:之前是用的wait(),后来运行时,发现最后总有一个线程牌阻塞状态,因此采用的wait(1000)。
代码如下:
运行结果:
Thread-1 1
Thread-0 2
Thread-1 3
Thread-0 4
Thread-1 5
Thread-0 6
Thread-1 7
Thread-0 8
Thread-1 9
Thread-0 10
解决方法: 通过wait(),notify()实现。
注:之前是用的wait(),后来运行时,发现最后总有一个线程牌阻塞状态,因此采用的wait(1000)。
代码如下:
package thread; public class ThreadTest { private static Object LOCK = new Object(); private static int i=1; public static void main(String[] args) { Thread thread1 = new Thread() { public void run() { while(i<=10) { synchronized (LOCK) { if(i%2==0){ System.out.println("Thread1: "+i++); }else{ LOCK.notifyAll(); try { LOCK.wait(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }; Thread thread2 = new Thread() { public void run() { while(i<=10) { synchronized (LOCK) { if(i%2!=0){ System.out.println("Thread2: "+i++); }else{ LOCK.notifyAll(); try { LOCK.wait(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }; thread1.start(); thread2.start(); } }
运行结果:
Thread-1 1
Thread-0 2
Thread-1 3
Thread-0 4
Thread-1 5
Thread-0 6
Thread-1 7
Thread-0 8
Thread-1 9
Thread-0 10
相关文章推荐
- ZooKeeper安装和配置(转)
- SQL数据库的十条命令
- hdu3535AreYouBusy【分组背包综合题】
- BB10 SDK离线安装步骤
- Java泛型与反射
- css 随内容自适应
- maven3+项目管理命令总结 (错误解决:Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:2)
- 【枚举】tyvj 1387 迷你火车头
- CSS3 圆形loading效果
- 第一次尝试节奏跑(乳酸门槛跑)
- 表单验证
- php多进程编程相关资料(以备参考)
- sqlite案例
- 27 Quadratic primes - Project Euler
- 路遥知马力
- MySQL添加外键
- 使用CoreImage实现素描滤镜
- 2015/11/4用Python写游戏,pygame入门(4):获取鼠标的位置及运动
- 贝塞尔曲线的讲解
- codeforce 590d