1.sleep和wait的区别

java多线程相关知识点
(1).sleep是Thread中的静态方法,谁调用谁去睡觉,即使在T1线程里调用了T2线程的sleep方法,
实际上还是T1去睡觉。
(2)sleep方法不会释放对象得锁,而wait方法释放了锁.
(3)wait,notify和notifyAll只能在同步控制方法或者同步控制块里面使用,而sleep可以在任何地方使用。

2.多线程练习

(1)子线程循环10次,接着主线程循环100,接着又回到子线程循环10次,接着再回到主线程又循环100,如此循环50次,请写出程序。

public class Test {

	public static void main(String[] args) {

		MyThread myThread = new MyThread();

		new Thread(new Runnable() {

			@Override
			public void run() {
				for (int i = 0; i < 50; i++) {
					try {
						myThread.subThread(i);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
		
		
		for(int i = 0; i < 50; i++) {
			try {
				myThread.mainThread(i);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}

class MyThread {

	private boolean isSubThread = true;

	public synchronized void subThread(int i) throws InterruptedException {

		if (!isSubThread) {
			this.wait();
		}

		for (int j = 0; j < 10; j++) {
			System.out.println("这是subThread>>>>" + i + "次循环," + "loop>>>" + j);
		}

		isSubThread = false;
		this.notify();
	}

	public synchronized void mainThread(int i) throws InterruptedException {

		if (isSubThread) {
			this.wait();
		}

		for (int j = 0; j < 100; j++) {
			System.out.println("这是MainThread>>>>" + i + "次循环," + "loop>>>" + j);
		}

		isSubThread = true;
		this.notify();
	}

}

未完待续…

相关文章:

  • 2021-12-13
  • 2022-12-23
  • 2022-12-23
  • 2021-08-09
  • 2022-02-14
  • 2021-11-17
  • 2021-07-14
  • 2021-09-07
猜你喜欢
  • 2021-06-26
  • 2021-07-05
  • 2021-05-26
  • 2022-12-23
  • 2022-02-15
  • 2021-06-01
相关资源
相似解决方案