設計四個線程,其中兩個線程執行加操作,兩個線程執行減操作

package com.multith.java;

public class Test04 implements Runnable {
	
	private static int count=0;
	
	@Override
	public void run() {
		while(true) {
			if(Thread.currentThread().getName().startsWith("add")) {
				count++;
			}else {
				count--;
			}
			System.out.println(count);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Test04 t = new Test04();
		
		Thread tt = new Thread(t,"add01");
		Thread tt2 = new Thread(t,"add02");
		Thread tt3 = new Thread(t,"mul03");
		Thread tt4 = new Thread(t,"mul04");
//		System.out.print("線程1:");
		tt.start();
		tt2.start();
		tt3.start();
		tt4.start();
		

	}

}

發佈了111 篇原創文章 · 獲贊 41 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章