1)有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABCABC…
2)假如有字符串“6sabcsssfsfs33” ,用最有快速的方法去掉字符“ab3”,不能用java内置字符串方法(indeOf,substring,replaceAll等)?
第一个题目主要考的是java多线程的知识。我们可以用操作系统中经典的生产者,消费者模式来解决
我们用一个队列来作为共享的资源,如果多个线程需要访问共享的资源,那么就需要我们对线程进行控制,也就是对线程的同步和互斥问题进行控制。
对于这个题目,我们可以将一个队列来生产ABC字符串,那么消费就对象的是打印ABC字符串。这样就和生产者,消费者模式很像。
下面是具体的代码
package com.chen106106.java;
import java.util.LinkedList;
public class Sycn1 {
private static int MAX = 1;
private static int COUNT = 10;
private LinkedList<Object> myList =new LinkedList<Object>();
public static int count = 0;
public Sycn1(){
}
public void init(){
Producer p = new Producer("p");
Consumer c = new Consumer("c");
p.start();
c.start();
}
public static void main(String[] args) throws Exception{
Sycn1 s3 = new Sycn1();
s3.init();
}
class Producer extends Thread{
Producer(String name){
super(name);
}
public void run(){
while(true){
synchronized(myList){
try{
if( COUNT < Sycn1.count ){
System.exit(0);
}
if(myList.size() == MAX){
//System.out.println("warning: it's full!");
myList.wait();
}
// Object o = new Object();
count++;
SharedOject o = new SharedOject("ABC");
myList.add(o);
//System.out.println("Producer: " + o);
// o.print();
myList.notify();
}catch(InterruptedException e){
System.out.println("producer is interrupted!");
}
}
}
}
}
class Consumer extends Thread{
public Consumer(String name){
super(name);
}
public void run(){
while(true){
synchronized(myList){
try{
if(myList.size() == 0){
//System.out.println("warning: it's empty!");
myList.wait();
}
//Object o = myList.take();
SharedOject o = (SharedOject) myList.removeLast();
//System.out.println("Consumer: " + o);
o.print();
myList.notify();
}catch(InterruptedException e){
System.out.println("producer is interrupted!");
}
}
}
}
}
class SharedOject{
public SharedOject(String value){
this.value = value;
}
public void print(){
//System.out.println(name+"-"+value+"-"+count);
System.out.print(value);
}
private String value;
private String name = Thread.currentThread().getName();
}
}
第二题 就是将字符串转为字符串数组,对每个字符进行评定,如果包含指定的字符ab3,那么就去掉。将满足条件的字符放到新的字符数组中。