java多线程问题,线程交替执行

两个线程,一个打印1-100的奇数,一个打印1-100的偶数;要求:线程1打印5个之后,线程2开始打印,线程2打印5个之后,线程1再开始打印,以此循环。

package threadtest;

public class Test1 {
	/*
	 * 两个线程,一个打印1-100的奇数,一个打印1-100的偶数;要求:线程1打印5个之后,线程2开始打印,线程2打印5个之后,线程1再开始打印,以此循环。
	 */
	private static int state = 1;
	private static int num1 = 1;
	private static int num2 = 2;
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		final Test1 t = new Test1();
		new Thread(new Runnable(){
			@Override
			public void run(){
				while(num1<100){
					//两个线程都用t对象作为锁,保证每个交替期间只有一个线程在打印
					synchronized(t){
						 // 如果state!=1, 说明此时尚未轮到线程1打印, 线程1将调用t的wait()方法, 直到下次被唤醒  
						if(state!=1){
							try{
								t.wait();
							}catch(InterruptedException e){
								e.printStackTrace();
							}
						}
						// 当state=1时, 轮到线程1打印5次数字
						for(int j=0;j<5;j++){
							System.out.println(num1);
							num1 +=2;
						}
						// 线程1打印完成后, 将state赋值为2, 表示接下来将轮到线程2打印  
                        state = 2;  
                        // notifyAll()方法唤醒在t上wait的线程2, 同时线程1将退出同步代码块, 释放t锁  
                        t.notifyAll();  
					}
				}
			}
		}).start();
		
		new Thread(new Runnable(){
			@Override
			public void run(){
				while(num2<100){
					synchronized(t){
						if(state!=2){
							try{
								t.wait();
							}catch(InterruptedException e){
								e.printStackTrace();
							}
						}
						
						for(int i=0;i<5;i++){
							System.out.println(num2);
							num2 +=2;
						}
						
						state=1;
						t.notifyAll();
					}
															
				}				
			}
		}).start();		
	}
}

两个线程交替打印。例如第一个线程打印1,接着第二个线程打印100,接着第一个线程打印2

package threadtest;

public class ThreadTest1 extends Thread{
	/*
	 * java多线程问题。两个线程交替打印。例如第一个线程打印1,接着第二个线程打印100,接着第一个线程打印2
	 */
	
	private static int num =0, n = 100;
	static ThreadTest1 t1, t2;
	static int i=0;
	static int x;
	static String ss = new String();
	
	public ThreadTest1(){
		start();
	}
	
	public void run(){
		for(x = 0;x<200;x++){
			synchronized(ss){
				ss.notify();
				Print();
				try{
					ss.wait();
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
		}
		synchronized(ss){
			ss.notifyAll();
		}
	}
	
	public void Print(){
		if(i==0){
			i++;
			System.out.println(this.getName()+":"+ ++num);
		}else{
			i=(i+1)%2;
			System.out.println(this.getName()+":" + n++);
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		t1 = new ThreadTest1();
		t2 = new ThreadTest1();
	}

}


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值