-
- package com.study.thread;
- public class MyThread
- {
- private static Count count = new Count(1);
- private static SubThread s = new SubThread(count);
- /**
- * 子线程循环10次,接着主线程循环100,接着又回到子线程循环10次,
- 接着再回到主线程又循环100,如此循环50次,请写出程序。
- */
- public static void main(String[] args) throws Exception
- {
- Thread t = new Thread(s, "子线程");
- t.start();
- Thread.sleep(1);
- mainFun();
- }
- private static void mainFun()
- {
- synchronized (count)
- {
- while (count.count <= 50)
- {
- for (int i = 0; i < 100; i++)
- {
- System.out.println(Thread.currentThread().getName() + "执行第" + (i + 1) + "次");
- }
- try
- {
- count.notify();
- count.wait();
- }
- catch (InterruptedException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- static class SubThread implements Runnable
- {
- Count count;
- public SubThread(Count count)
- {
- this.count = count;
- }
- public void run()
- {
- synchronized (count)
- {
- while (count.count <= 50)
- {
- System.out.println("第" + count.count + "次循环----------------------");
- count.count++;
- for (int i = 0; i < 10; i++)
- {
- System.out.println(Thread.currentThread().getName() + "执行第" + (i + 1) + "次");
- }
- try
- {
- count.notify();
- count.wait();
- }
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- }
- }
- }
- }
- static class Count
- {
- int count;
- public Count(int count)
- {
- this.count = count;
- }
- public int getCount()
- {
- return count;
- }
- }
- }
线程面试题目
最新推荐文章于 2024-09-17 14:53:38 发布