java 面试题,不太会!
设计两个线程,对一个初始值为1的整型变量进行操作,一个线程对变量i进行自加操作,另一个线程对变量i进行自减的操作,要求在程序中变量的值符合010101010。。。。的规则变化 java 线程 面试题 设计
[解决办法]
哈,这题我在写代码玩的时候写过类似的,要写对是不容易,而且看题目要求,楼上的说法应该不能得分。程序里面不能有任何对于数值判断的操作,否则这题就没意思了
[解决办法]
好吧因为之前说了这句话,所以不得不写一个并非完美的解法。。。其实判断还是要的,只是不会每一次被唤醒都要做判断
package test;
public class Test implements Runnable {
private static int iValue = 0;
private static Object iLock = new Object();
private final int iStepSize;
public Test(final int stepSize) {
iStepSize = stepSize;
}
@Override
public void run() {
while (true) {
System.out.print(iValue);
iValue += iStepSize;
synchronized (iLock) {
iLock.notifyAll();
try {
iLock.wait();
}
catch (InterruptedException e) {
}
}
}
}
public static void main(final String[] args) throws Exception {
Thread t1 = new Thread(new Test(1));
Thread t2 = new Thread(new Test(-1));
t1.start();
Thread.sleep(100);
t2.start();
Thread.sleep(500);
}
}
public class Test {
int i = 1;
public synchronized void calcNumber() {
if (i != 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i++;
System.out.print(i);
notify();
}
public synchronized void calcNumber2() {
if (i != 1) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i--;
System.out.print(i);
notify();
}
}
public class Thread1 implements Runnable {
Test t;
public Thread1(Test t) {
this.t = t;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
t.calcNumber();
}
}
}
public class Thread2 implements Runnable {
Test t;
public Thread2(Test t) {
this.t = t;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
t.calcNumber2();
}
}
}
/**
* 测试类
* @author Administrator
*
*/
public class Test2 {
/**
* @param args
*/
public static void main(String[] args) {
Test t = new Test();
new Thread(new Thread2(t)).start();
new Thread(new Thread1(t)).start();
}
}
public class thread {
private int j=0;
private static Object iLock = new Object();
public static void main(String[] args) {
thread incDec=new thread();
Inc inc=incDec.new Inc();
Dec dec=incDec.new Dec();
while(true){
Thread thread=new Thread(inc);
thread.start();
thread=new Thread(dec);
thread.start();
}
}
public synchronized void inc(){
j++;
System.out.println(Thread.currentThread().getName()+"-inc:"+j);
}
public synchronized void dec(){
j--;
System.out.println(Thread.currentThread().getName()+"-dec:"+j);
}
class Inc implements Runnable{
public void run(){
synchronized (iLock) {
if(j==0){
j++;
System.out.println(Thread.currentThread().getName()+"-inc:"+j);
iLock.notifyAll();
try {
iLock.wait();
}
catch (InterruptedException e) {
}
}
}
}
}
class Dec implements Runnable{
public void run(){
synchronized (iLock) {
if(j==1){
j--;
System.out.println(Thread.currentThread().getName()+"-dec:"+j);
iLock.notifyAll();
try {
iLock.wait();
}
catch (InterruptedException e) {
}
}
}
}
}
}