首页 技术 正文
技术 2022年11月15日
0 收藏 835 点赞 4,805 浏览 1397 个字

面试题:

子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着又 主线程循环100次,如此循环50次,请写出程序

/**
* 子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着又 主线程循环100次,如此循环50次,请写出程序
*
* @author Administrator
*
*/
public class TraditionalThreadCommunication { public static void main(String[] args) {
final Business business = new Business();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 50; i++) {
business.sub(i);
}
}
}).start(); for (int i = 1; i <= 50; i++) {
business.main(i);
}
}}
/**
* 记住一个原则,把他们放到一个类上,自己管理自己的状态,不要让外边的线程去管
*/
class Business {
private boolean isShoudeSub = true; /**
* 同步加在需要访问的资源的代码上,不要放在线程上
   * 这样的好处是:以后我这个类 交给任何一个线程去访问,自然就同步了,不用考虑线程同步问题
* @param i
*/
public synchronized void sub(int i) {
while (!isShoudeSub) { //这里也可以用 if ,用while比较好一些 As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop
try { // 防止线程有可能被假唤醒 (while放在这里提现了水准)
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 100; j++) {
System.out
.println("sub thread sequence of " + j + ", loop of " + i);
}
isShoudeSub = false;
this.notify();
} public synchronized void main(int i) {
while (isShoudeSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("main thread sequence of " + j + ", loop of "
+ i);
}
isShoudeSub = true;
this.notify();
}
/**
*
* synchronized (obj) { 这里的obj与obj.wait必须是同一个对象,否则会抛异常
while (<condition does not hold>)
obj.wait();
... // Perform action appropriate to condition
} */
}

经验:要用到共同数据(包括同步锁)或共同算法的若干个方法应该归在同一个类身上,这种设计正好提现了高类聚和程序的健壮性。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,086
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,561
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,410
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,183
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,820
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,903