迅雷笔试题(JAVA多线程)启动三个线程,分别打印ABC,现在写⼀个程序循环打印ABCABCABC
题⽬:wenku.baidu/view/d66187aad1f34693daef3e8a.html
启动三个线程,分别打印A B C,现在写⼀个程序循环打印
本⽂分别使⽤wait、nofity和Semaphore来实现:
wait、nofity版本
public class TestThread {
public static void main(String[] args) {
new Thread(new OrderThread(0,'A')).start();
new Thread(new OrderThread(1,'B')).start();
new Thread(new OrderThread(2,'C')).start();
}
}
class OrderThread implements Runnable {
//定义⼀个类静态变量的锁对象
private static Object o = new Object();
//类静态变量、⽤来记录是哪个线程进⼊运⾏
replaceall()
private static int count = 0;
//每个线程的标识,名称
private char ID;
//⽤来控制是线程运⾏的标识
private int id;
//每个线程运⾏的次数
private int num = 0;
public OrderThread(int id,char ID) {
this.id = id;
this.ID = ID;
}
public void run() {
synchronized (o) {
while (num < 10) {
if(count % 3 == id){
System.out.print(ID);
++ count;
++ num;
}
else{
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
Semaphore版本
public class ThreadSync {
static class ConditionThread extends Thread {
private Semaphore preCond;
private Semaphore postCond;
ConditionThread(Semaphore preCond, Semaphore postCond, String name) {
this.preCond = preCond;
this.postCond = postCond;
this.setName(name);
}
public void run() {
for (int i = 0; i < 10; i++) {
try {
preCond.acquire();
System.out.print(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Semaphore semaphoreA = new Semaphore(0);
Semaphore semaphoreB = new Semaphore(0);
Semaphore semaphoreC = new Semaphore(1);
Thread threadA = new ConditionThread(semaphoreC, semaphoreA, "A");
Thread threadB = new ConditionThread(semaphoreA, semaphoreB, "B");
Thread threadC = new ConditionThread(semaphoreB, semaphoreC, "C");
threadA.start();
threadB.start();
threadC.start();
// threadA.join();
// threadB.join();
// threadC.join();
}
}
2,假如有字符串“6sabcsssfsfs33” ,⽤最有快速的⽅法去掉字符“ab3”,不能⽤java内置字符串⽅法(indeOf,substring,replaceAll等)package com.kingdee.al;
public class Test {
public static void main(String[] args) {
String str = "6sabcsssfsfs33";
char[] array = { 'a', 'b', '3' };
char[] newArray = CharArray();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < newArray.length; i++) {
boolean isMatch = false;
for (char key : array){
if (newArray[i] == key)
isMatch = true;
}
if(!isMatch){
sb.append(newArray[i]);
}
}
System.out.String());
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。