面试时遭遇多线程

最近正忙于找工作,前天参加了迅雷的笔试,里面考到的很多东西都忘记了,惭愧啊~~~
记得最后一题是有关多线程调度的,做web应用做久了,多线程也仅限于简单的轮询,而没有做过什么调度的事,结果当然是做不出来了。 回来后痛定思痛,找了多线程方面的书研究了一下,发现其实也不是太难。有个同事说过,要在面试中成长。亡羊补牢,这也算是一种进步吧,虽然有点后知后觉。
记得题目是这样的:创建三个线程分别为A,B,C, 要求打印输入如下结果:ABCABCABC
我现在写了个简单的例子,实现了这个要求:
代码为:

class PrintMsg implements Runnable {
//开始打印
public synchronized void startPrint() {
notify();
}

@Override
public synchronized void run() {
for (int i = 0; i < 10; i++) {
try {
wait();
System.out.print(Thread.currentThread().getName());
notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class ThreadDemo {
public static void main(String[] args) throws Exception {
PrintMsg printMsg = new PrintMsg();
Thread threadA = new Thread(printMsg, "A");
Thread threadB = new Thread(printMsg, "B");
Thread threadC = new Thread(printMsg, "C");

threadA.start();
Thread.sleep(100);//休眠,保证thread进入wait堆栈的顺序

threadB.start();
Thread.sleep(100);

threadC.start();
Thread.sleep(100);

printMsg.startPrint();
}
}

代码运行结果为:

ABCABCABCABCABCABCABCABCABCABC
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值