大家好,小跳来为大家解答以上的问题。java多线程编程面试题,java多线程面试题这个很多人还不知道,现在让我们一起来看看吧!
1、我不知道你是不是这个意思,thread1,thread2两个线程每次让j增加1,thread3,thread4两个线程每次让j减少1,四个线程每个都调用250次相关加减一操作。
2、最终j的结果都是100.下面程序,总计会打印出1000个数,不管怎么样最后一个数永远是100,即j的终值永远是100,为了看中间结果运行过程我加了sleep,但无关紧要。
3、你看看符合你要求不?就像楼上说的,启动1000条线程不是很明白,不一致的继续讨论package com.kalort;public class ThreadTest{ public static void main(String[] args) { Operator operator = new Operator(); Thread thread1 = new IncreaseThread(operator); Thread thread2 = new IncreaseThread(operator); Thread thread3 = new DecreaseThread(operator); Thread thread4 = new DecreaseThread(operator); thread1.start(); thread2.start(); thread3.start(); thread4.start(); }}class IncreaseThread extends Thread{ private Operator operator; public IncreaseThread(Operator operator) { this.operator = operator; } public void run() { for (int i = 0; i < 250; i++) { try { Thread.sleep((long)(Math.random() * 100)); } catch (InterruptedException e) { e.printStackTrace(); } operator.increase(); } }}class DecreaseThread extends Thread{ private Operator operator; public DecreaseThread(Operator operator) { this.operator = operator; } public void run() { for (int i = 0; i < 250; i++) { try { Thread.sleep((long)(Math.random() * 100)); } catch (InterruptedException e) { e.printStackTrace(); } operator.decrease(); } }}class Operator{ private int j = 100; public synchronized void increase() { while (100 != j) { try { wait(); // 如果另外线程还没减一就等待 } catch (InterruptedException e) { e.printStackTrace(); } } j++; System.out.println(j); notify(); // 通知另外线程已经加一了。
4、 } public synchronized void decrease() { while (100 == j) { try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } j--; System.out.println(j); notify(); }}。
本文到此分享完毕,希望对大家有所帮助。