zoukankan      html  css  js  c++  java
  • 使用Java 多线程编程 让三个线程轮流输出ABC,循环10次后结束

    简要分析:

    要求三个线程轮流输出,这里我们要使用一个对象锁,让关键部分的代码放入同步块当中。同时要有一个变量记录打印的次数到达10次循环后不再打印,另外一个就是要给每个线程一个标志号,我们根据标识号来输出对应的信息。

    package com.test;
    
    public class PrintOneTwoThree {
    	public static void main(String[] args) {
    		Print p1 = new Print(0);
    		Print p2 = new Print(1);
    		Print p3 = new Print(2);
    
    		new Thread(p1, "p1").start();
    		new Thread(p2, "p2").start();
    		new Thread(p3, "p3").start();
    
    		while (Thread.activeCount() > 1)
    			;
    		System.out.println("Done!");
    	}
    }
    
    class Print implements Runnable {
    	private static int state = 0;
    	private int id;
    	private static Object lock = new Object();
    
    	public Print(int id) {
    		this.id = id;
    	}
    
    	@Override
    	public void run() {
    		synchronized (lock) {
    			while (state < 30) {
    				if (state % 3 == id) {
    					switch (id) {
    					case 0:
    						System.out.println("["
    								+ Thread.currentThread().getName() + "]" + "A");
    						break;
    
    					case 1:
    						System.out.println("["
    								+ Thread.currentThread().getName() + "]" + "B");
    						break;
    						
    					case 2:
    						System.out.println("["
    								+ Thread.currentThread().getName() + "]" + "C");
    						break;
    
    					default:
    						break;
    					}
    					state++;
    					lock.notifyAll();
    				} else {
    					try {
    						lock.wait();
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    				}
    			}
    		}
    	}
    }
    

      

  • 相关阅读:
    promise实现(未实现微任务)
    fastclick猜的原理
    js进制
    如何造一个好的组件库【有空就更新】
    BEM的命名
    unicode、utf-32、utf-8、utf-16
    getElementsByTagName、getElementsByClassName与querySelectorAll的区别
    为什么vue中没有事件委托/事件代理的概念
    vscode注释param
    复制dom
  • 原文地址:https://www.cnblogs.com/fangying7/p/4750826.html
Copyright © 2011-2022 走看看