class LoadDown implements Runnable{ static double num=0; static double n1 =0; static double n2 =0; static double n3 =0; static double n4 =0; public void run(){ while(true){ synchronized ("锁") { if (num<=500) { try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(Thread.currentThread().getName().equals("下载线程一")){ n1 +=1; }else if (Thread.currentThread().getName().equals("下载线程二")) { n2 +=1; }else if(Thread.currentThread().getName().equals("下载线程三")) { n3 +=1; }else if(Thread.currentThread().getName().equals("下载线程四")) { n4 +=1; } System.out.println(Thread.currentThread().getName()+"已下载"+(num/500)*100+"%"); num++; }else{ System.out.println("已经下载完成"); break; } } } System.out.println("每个线程各下载: "+(n1/500)*100+"%"+"\t\t"+(n2/500)*100+"%"+"\t"+(n3/500)*100+"%"+"\t"+(n4/500)*100+"%"+"\t"); System.out.println(n1+" "+n2+" "+n3+" "+n4); } } public class demo1 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub LoadDown loadDown =new LoadDown(); Thread thread1=new Thread(loadDown,"下载线程一"); Thread thread2=new Thread(loadDown,"下载线程二"); Thread thread3=new Thread(loadDown,"下载线程三"); Thread thread4=new Thread(loadDown,"下载线程四"); thread1.start(); thread2.start(); thread3.start(); thread4.start(); } }
时间: 2024-11-19 23:19:00