首页 > 代码库 > Java多线程,线程交替执行
Java多线程,线程交替执行
两个线程,一个打印1-100的奇数,一个打印1-100的偶数;要求:线程1打印5个之后,线程2开始打印,线程2打印5个之后,线程1再开始打印,以此循环。
Code:
package com.qhong;public class Main { /* * 两个线程,一个打印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 Main t=new Main(); 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(); }}
Output:
135792468101113151719121416182021232527292224262830313335373932343638404143454749424446485051535557595254565860616365676962646668707173757779727476788081838587898284868890919395979992949698100
http://blog.csdn.net/junli_chen/article/details/49584187
Java多线程,线程交替执行
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。