专注Java教育14年 全国咨询/投诉热线:400-8080-105
动力节点LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 面试常出现的Java上机练习题及答案

面试常出现的Java上机练习题及答案

更新时间:2020-08-19 15:57:42 来源:动力节点 浏览1927次

⒈  写一个冒泡排序方法

【参考答案】

publicstaticvoid Bubble(int a[]){
for (int i = 0; i < a.length; i++) {
for (int j = a.length-1; j>i;j++) {
if (a[j]

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

publicclass ThreadTest {
publicstaticvoid main(String[] args) {
new ThreadTest().init();
}
publicvoid init(){
final Business business=new Business();
new Thread(
new Runnable(){
@Override
publicvoid run() {
for (int i = 0; i < 50; i++) {
business.SubThread(i);
}
}
}
).start();
for (int i = 0; i < 50; i++) {
business.MainThread(i);
}
}
privateclass Business{
booleanbShouldSub=true;//这里相当于定义了控制该谁执行的一个信号灯
publicsynchronizedvoid MainThread(int i){
if (bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int j = 0; j < 5; j++) {
System.err.println(Thread.currentThread().getName()+":i="+i+",j="+j);
}
bShouldSub=true;
this.notify();
}
}
publicsynchronizedvoid SubThread(int i1){
if (!bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int j = 0; j < 10; j++) {
System.err.println(Thread.currentThread().getName()+":i="+i1+",j="+j);
}
bShouldSub=false;
this.notify();
}
}
}
}

备注:不可能一上来就写出以上代码,最初写出来的代码如下,问题在于两个线程的代码要参照同一个变量,即这两个线程要共享数据,所以,把这两个线程的执行代码搬到同一个类中区:

publicclass thread {
privatestaticbooleanbShouldMain=false;
publicstaticvoid main(String[] args) {
/*new Thread(){
public void run() {
for (int i = 0; i < 50; i++) {
for (int j = 0; j < 10; j++) {
System.out.println("i="+i+",j="+j);
}
}
}
}.start();*/
//final String str =new String("");
new Thread(new Runnable() {
publicvoid run() {
for (int i = 0; i < 50; i++) {
synchronized (Thread.class) {
if (bShouldMain) {
try {
ThreadTest.class.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int j = 0; j < 10; j++) {
System.out.println(Thread.currentThread().getName()+":i="+i+",j="+j);
}
bShouldMain=true;
ThreadTest.class.notify();
}
}
}
}).start();
for (int i = 0; i < 50; i++) {
if (!bShouldMain) {
try {
ThreadTest.class.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int j = 0; j <5; j++) {
System.out.println(Thread.currentThread().getName()+":i="+i+",j="+j);
}
bShouldMain=false;
ThreadTest.class.notify();
}
}
}

以上就是动力节点java培训机构的小编针对“面试常出现的Java上机练习题及答案”的内容进行的回答,希望对大家有所帮助,如有疑问,请在线咨询,有专业老师随时为你服务。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>