计数器,从1-100之间计数,每个1秒计数一次
public class MyThread extends Thread {
public void run ( ) {
for ( int i = 0 ; i < 100 ; i++ ) {
System . out. print ( i) ;
try {
Thread . sleep ( 1000 ) ;
System . out. print ( " 线程睡眠1000毫秒!\n" ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
}
public static void main ( String [ ] args) {
new MyThread ( ) . start ( ) ;
}
创建工厂类,属性包括:车间类的对象的集合,仓库容量 方法包括:
加工玩具的方法(product),方法的功能是各个车间同时工作。根据仓库容量平均分配给各个车间需要加工玩具的数量。 建造玩具车间的方法(createWorkshop),方法功能是模拟建造玩具生成车间,即向集合属性中添加一个新车间。
使用多线程模拟加工玩具的功能,假设每隔2秒可完成一个玩具的加工,每个车间完成一个玩具的加工后,打印当前已加工玩具数量(给每个线程设置名称为车间的名称) 创建测试类,模拟工厂加工玩具的功能。
import java. util. ArrayList ;
import java. util. Scanner ;
public class Factory {
private int capability= 12 ;
private Work [ ] shop = new Work [ 4 ] ;
private static ArrayList < Work > shopList = new ArrayList < Work > ( ) ;
private int Worknum = 0 ;
public int getWorknum ( ) {
return Worknum ;
}
public void setWorknum ( int num_w) {
Worknum = num_w;
}
public int getcapability ( ) {
return capability;
}
public void setcapability ( int num_c) {
capability= num_c;
}
public Work [ ] getShop ( ) {
return shop;
}
public void setShop ( Work [ ] shop) {
this . shop = shop;
}
public static ArrayList < Work > getShopList ( ) {
return shopList;
}
public static void setShopList ( ArrayList < Work > shopList) {
Factory . shopList = shopList;
}
public Factory ( ) {
}
public Factory ( int capability) {
this . capability= capability;
}
public int num_average ( ) {
int average= this . capability/ this . shopList. size ( ) ;
return average;
}
public void createWorkshop ( String name) {
int i = this. Worknum;
this . shop[ i] = new Work ( ) ;
this . shop[ i] . setname ( name) ;
shopList. add ( shop[ i] ) ;
this. Worknum++ ;
}
public void product ( ) {
for ( int i= 0 ; i< Worknum ; i++ ) {
Thread shopThread = new Thread ( shop[ i] ) ;
shopThread. start ( ) ;
}
}
}
import java. util. Scanner ;
public class Work extends Factory implements Runnable {
private String name;
public String getname ( ) {
return name;
}
public void setname ( String name) {
this . name= name;
}
public Work ( ) {
}
public Work ( String name) {
this . name = name;
}
@Override
public void run ( ) {
int j= num_average ( ) ;
System . out. println ( Thread . currentThread ( ) . getName ( ) ) ;
for ( int i= 0 ; i< j; i++ ) {
try {
Thread . sleep ( 2000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
int sum= i+ 1 ;
System . out. println ( this . name+ "已经生产了" + sum + "件" ) ;
if ( i== num_average ( ) - 1 ) {
System . out. println ( this . name+ "生产完毕" ) ;
}
}
}
}
import java. util. Scanner ;
public class Test {
public static void main ( String [ ] args) {
Factory plays= new Factory ( ) ;
String name1 = "车间一" ;
String name2 = "车间二" ;
String name3 = "车间三" ;
String name4 = "车间四" ;
plays. createWorkshop ( name1) ;
plays. createWorkshop ( name2) ;
plays. createWorkshop ( name3) ;
plays. createWorkshop ( name4) ;
plays. product ( ) ;
}
}