两个线程每隔一秒交替打印

1、实现Runnable接口,对其中的run方法加同步锁。

class RunnableDemo implements Runnable {
	
	public void run() {
		//start两线程交替打印1
		synchronized (this) {
			int a = 0;
			for(int i=0;i<50;i++) {
				try {
					Thread.sleep(1000);
					if(a==1) {
						wait();
						a=0;
					}
					notify();
					if(a==0) {
						System.out.println(Thread.currentThread().getName() + ":"+i);
						a=1;
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

2、实例化两个线程,strat()。

public class ThreadDemo03 {
	public static void main(String[] args) {
		RunnableDemo r1 = new RunnableDemo();
		Thread t1 = new Thread(r1,"A");
		Thread t2 = new Thread(r1,"B");
		t1.start();
		t2.start();
	}

}

3、刚学线程,不知道这样有没什么遗漏,欢迎高手指出

猜你喜欢

转载自blog.csdn.net/qq_28562411/article/details/81840144