题目要求
1. 编写一个实现了Runnable接口的类,这个类中包含3个线程,3个线程的名字是“张工”,“王工”和“老板”。线程“张工”和线程“王工”分别负责“搬运苹果”(3箱)和“搬运香蕉”(3箱),他们每搬运一箱,就准备休息10秒钟(sleep方法),但是线程“老板”负责不让他们休息(interrupt方法)。
2. 编写一个包含主方法main的公共类(访问权限为public的类),在主方法main中,使用第1步中编写的类创建一个对象,使用这个对象调用线程“张工”,“王工”和“老板”,并启动线程(start)。
注意事项:
实例化thread类对象的时候,应用Thread a=new Thread (this);
注意()中的this!!!!
public Thread()
-
Allocates a new
Thread
object. This constructor has the same effect asThread(null, null,
gname)
, where gname is a newly generated name. Automatically generated names are of the form"Thread-"+
n, where n is an integer.
public Thread(Runnable target)
-
Allocates a new
Thread
object. This constructor has the same effect asThread(null, target,
gname)
, where gname is a newly generated name. Automatically generated names are of the form"Thread-"+
n, where n is an integer.-
Parameters:
-
target
- the object whoserun
method is called.
-
因此想要调用run方法的时候必须声明target
-
源代码
public class ex5 {
public static void main(String []args){
th th=new th();
th.a.start();
th.b.start();
th.c.start();
}
}
class th implements Runnable{
Thread a,b,c;
th(){
a=new Thread(this); //new thread时候必须加this
b=new Thread(this);
c=new Thread(this);
a.setName("张工");
b.setName("王工");
c.setName("老板");
}
public void run(){
if(Thread.currentThread()==a)
for(int i=1;i<4;i++)
{
System.out.println("张工已搬运了"+i+"箱苹果");
try {
a.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
if(i!=3)
System.out.println("老板让张工继续工作");
}
}
else if(Thread.currentThread()==b)
for(int i=1;i<4;i++)
{
System.out.println("王工已搬运了"+i+"箱苹果");
try {
b.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
if(i!=3)
System.out.println("老板让王工继续工作");
}
}
else if(Thread.currentThread()==c){
while(true){
if(a.isAlive()||b.isAlive())
{
a.interrupt();
b.interrupt();
}
else break;
}
System.out.println("老板说:可以下班了");
}
}
}