第九章Java多线程机制
例子1
publicclassExample9_1
{publicstaticvoidmain(Stringargs[])
{Lefthandleft;
Righthandright;
left=newLefthand();//创建线程
right=newRighthand();
left.start();
right.start();
for(inti=1;i<=6;i++)
{System.out.println("我是主线程");
}
}
}
classLefthandextendsThread
{publicvoidrun()
{for(inti=1;i<=9;i++)
{
System.out.println("我是左手线程");
}
}
}
classRighthandextendsThread
{publicvoidrun()
{for(inti=1;i<=9;i++)
{System.out.println("我是右手线程");
}
}
}
例子2
publicclassExample9_2
{publicstaticvoidmain(Stringargs[])
{Peopleteacher,student;
ComputerSumsum=newComputerSum();
teacher=newPeople("老师",200,sum);
student=newPeople("学生",200,sum);
teacher.start();
student.start();
}
}
classComputerSum
{intsum;
publicvoidsetSum(intn)
{sum=n;
}
publicintgetSum()
{returnsum;
}
}
classPeopleextendsThread
{inttimeLength;//线程休眠的时间长度
ComputerSumsum;
People(Strings,inttimeLength,ComputerSumsum)
{setName(s);//调用Thread类的方法setName为线程起个名字
this.timeLength=timeLength;
this.sum=sum;
}
publicvoidrun()
{for(inti=1;i<=5;i++)
{intm=sum.getSum();
sum.setSum(m+1);
System.out.println("我是"+getName()+",现在的和:"+sum.getSum());
try{sleep(timeLength);
}
catch(InterruptedExceptione){}
}
}
}
例子3
publicclassExample9_3
{publicstaticvoidmain(Stringargs[])
{Bankbank=newBank();
//线程的目标对象设置被线程共享的money
bank.setMoney(300);
bank.会计.start();
bank.出纳.start();
}
}
classBankimplementsRunnable
{privateintmoney=0;
Thread会计,出纳;
Bank()
{会计=newThread(this);
会计.setName("会计");
出纳=newThread(this);//会计和出纳的目标对象相同
出纳.setName("出纳");
}
publicvoidsetMoney(intmount)
{money=mount;
}
publicvoidrun()//接口中的方法
{while(true)
{money=money-50;
if(Thread.currentThread()==会计)
{System.out.println("我是"+会计.getName()+"现在有:"+money+"元");
if(money<=150)
{System.out.println(会计.getName()+"进入死亡状态");
return;//如果money少于50,会计的run方法结束
}
}
elseif(Thread.currentThread()==出纳)
{System.out.println("我是"+出纳.getName()+"现在有:"+money+"元");
if(money<=0)
return;//如果money少于0,出纳的run方法结束
}
try{Thread.sleep(800);
}
catch(InterruptedExceptione){}
}
}
}
例子4
classExample9_4
{publicstaticvoidmain(Stringargs[])
{ThreadthreadA,threadB,threadC,threadD;
TargetObjecta1=newTargetObject(),//线程的目标对象
a2=newTargetObject();
threadA=newThread(a1);//目标对象是a1的线程
threadB=newThread(a1);
a1.setNumber(10);
threadA.setName("add");
threadB.setName("add");
threadC=newThread(a2);//目标对象是a2的线程
threadD=newThread(a2);
a2.setNumber(-10);
threadC.setName("sub");
threadD.setName("sub");
threadA.start();
threadB.start();
threadC.start();
threadD.start();
}
}
classTargetObjectimplementsRunnable
{
privateintnumber=0;
publicvoidsetNumber(intn)
{number=n;
}
publicvoidrun()
{while(true)
{if(Thread.currentThread().getName().equals("add"))
{number++;
System.out.println("现在number等于"+number);
}
if(Thread.currentThread().getName().equals("sub"))
{number--;
System.out.println("现在number等于"+number);
}
try{Thread.sleep(1000);
}
catch(InterruptedExceptione)
{
}
}
}
}
例子5
classExample9_5
{publicstaticvoidmain(Stringargs[])
{Movemove=newMove();
move.zhangsan.start();
move.lisi.start();
}
}
classMoveimplementsRunnable
{Threadzhangsan,lisi;
Move()
{zhangsan=newThread(this);
zhangsan.setName("张三");
lisi=newThread(this);
lisi.setName("李四");
}
publicvoidrun()
{inti=0;
while(i<=5)
{if(Thread.currentThread()==zhangsan)
{i=i+1;
System.out.println(zhangsan.getName()+"线程的局部变量i="+i);
}
elseif(Thread.currentThread()==lisi)
{i=i+1;
System.out.println(lisi.getName()+"线程的局部变量i="+i);
}
try{Thread.sleep(800);
}
catch(InterruptedExceptione){}
}
}
}
例子6
publicclassExample9_6
{publicstaticvoidmain(Stringargs[])
{Numbernumber=newNumber();
number.giveNumberThread.start();
number.guessNumberThread.start();
}
}
classNumberimplementsRunnable
{
intrealNumber,guessNumber,min=0,max=100,message;
finalintSMALLER=-1,LARGER=1,SUCCESS=8;
ThreadgiveNumberThread,guessNumberThread;
Number()
{giveNumberThread=newThread(this);
guessNumberThread=newThread(this);
}
publicvoidrun()
{
for(intcount=1;true;count++)
{
if(Thread.currentThread()==giveNumberThread)
{
if(count==1)
{realNumber=(int)(Math.random()100)+1;
System.out.println("随机给你一个数,猜猜是多少?");
}
else
{if(realNumber>guessNumber)
{message=SMALLER;
System.out.println("你猜小了");
}
elseif(realNumber {message=LARGER;
System.out.println("你猜大了");
}
else
{message=SUCCESS;
System.out.println("恭喜,你猜对了");
return;
}
}
try{Thread.sleep(1500);
}
catch(Exceptione){}
}
if(Thread.currentThread()==guessNumberThread)
{
if(count==1)
{guessNumber=(min+max)/2;
System.out.println("我第"+count+"次猜这个数是:"+guessNumber);
}
else
{if(message==SMALLER)
{min=guessNumber;
guessNumber=(min+max)/2;
System.out.println("我第"+count+"次猜这个数是:"+guessNumber);
}
elseif(message==LARGER)
{max=guessNumber;
guessNumber=(min+max)/2;
System.out.println("我第"+count+"次猜这个数是:"+guessNumber);
}
elseif(message==SUCCESS)
{System.out.println("我成功了!");
return;
}
}
try{Thread.sleep(1500);
}
catch(Exceptione){}
}
}
}
}
例子7
classExample9_7
{publicstaticvoidmain(Stringargs[])
{ComputerSumsum=newComputerSum();
sum.computer1.start();
}
}
classComputerSumimplementsRunnable
{
Threadcomputer1,computer2;
inti=1,sum=0;
ComputerSum()
{computer1=newThread(this);
computer2=newThread(this);
}
publicvoidrun()
{while(i<=10)
{sum=sum+i;
System.out.println(sum);
i++;
if(i==6&&Thread.currentThread()==computer1)
{System.out.println(computer1.getName()+"完成任务了!");
computer2.start();
return;
}
}
}
}
例子8
importjava.util.;
publicclassExample9_8
{publicstaticvoidmain(Stringargs[])
{Aa=newA();
a.thread.start();
}
}
classAimplementsRunnable
{Threadthread;
intn=0;
A()
{thread=newThread(this);
}
publicvoidrun()
{while(true)
{System.out.println(newDate());
n++;
try{Thread.sleep(1000);
}
catch(InterruptedExceptione){}
if(n==3)
{thread=newThread(this);
thread.start();
}
if(n>=12)
return;
}
}
}
例子9
publicclassExample9_9
{publicstaticvoidmain(Stringargs[])
{Aa=newA();
a.student.start();
a.teacher.start();
}
}
classAimplementsRunnable
{Threadstudent,teacher;
A()
{teacher=newThread(this);
student=newThread(this);
teacher.setName("王教授");
student.setName("张三");
}
publicvoidrun()
{if(Thread.currentThread()==student)
{try{System.out.println(student.getName()+"正在睡觉,不听课");
Thread.sleep(10006060);
}
catch(InterruptedExceptione)
{System.out.println(student.getName()+"被老师叫醒了");
}
System.out.println(student.getName()+"开始听课");
}
elseif(Thread.currentThread()==teacher)
{
for(inti=1;i<=3;i++)
{System.out.println("上课!");
try{Thread.sleep(500);
}
catch(InterruptedExceptione){}
}
student.interrupt();//吵醒student
}
}
}
例子10
importjava.awt.;
importjava.awt.event.;
publicclassExample9_10
{publicstaticvoidmain(Stringargs[])
{newThreadFrame();
}
}
classThreadFrameextendsFrameimplementsActionListener,Runnable
{TextFieldtext1,text2;
booleanboo;
Labellabel=
newLabel("欢迎使用本字典");
Buttonfast=newButton("加速");
ThreadScrollwords=null;
ThreadFrame()
{setLayout(newFlowLayout());
Scrollwords=newThread(this);
text1=newTextField(10);
text2=newTextField(10);
add(text1);
add(text2);
add(fast);
add(label);
text1.addActionListener(this);
fast.addActionListener(this);
setBounds(100,100,400,280);
setVisible(true);
validate();
addWindowListener(newWindowAdapter()
{publicvoidwindowClosing(WindowEvente)
{System.exit(0);
}
});
Scrollwords.start();
}
publicvoidrun()
{while(true)
{intx=label.getBounds().x;
inty=120;
x=x+5;
label.setLocation(x,y);
if(x>380)
{x=10;
label.setLocation(x,y);
}
try{Scrollwords.sleep(1000);
}
catch(InterruptedExceptione){}
if(boo)
{return;//结束run方法,导致线程死亡。
}
}
}
publicvoidactionPerformed(ActionEvente)
{if(text1.getText().equals("boy"))
{text2.setText("男孩");
}
elseif(text1.getText().equals("die"))
{boo=true;
}
else
{text2.setText("没有该单词");
}
if(e.getSource()==fast)
{Scrollwords.interrupt();//吵醒休眠的线程,以便加快字模的滚动
}
}
}
例子11
importjava.awt.;
importjava.awt.event.;
publicclassExample9_11
{publicstaticvoidmain(Stringargs[])
{MyFrameframe=newMyFrame();
frame.setBounds(10,10,500,500);
frame.setVisible(true);
frame.addWindowListener(newWindowAdapter()
{publicvoidwindowClosing(WindowEvente)
{System.exit(0);
}
});
}
}
classMyFrameextendsFrameimplementsRunnable
{Thread红色球,兰色球;
MyCanvasred,blue;
doublet=0;
MyFrame()
{红色球=newThread(this);
兰色球=newThread(this);
red=newMyCanvas(Color.red);
blue=newMyCanvas(Color.blue);
setLayout(null);
add(red);
add(blue);
red.setLocation(60,100);
blue.setLocation(60,100);
红色球.start();
兰色球.start();
}
publicvoidrun()
{while(true)
{t=t+0.2;
if(t>20)t=0;
if(Thread.currentThread()==红色球)
{intx=60;
inth=(int)(1.0/2tt3.8)+60;
red.setLocation(x,h);
try{红色球.sleep(50);
}
catch(InterruptedExceptione){}
}
elseif(Thread.currentThread()==兰色球)
{intx=60+(int)(26t);
inth=(int)(1.0/2tt3.8)+60;
blue.setLocation(x,h);
try{兰色球.sleep(50);
}
catch(InterruptedExceptione){}
}
}
}
}
classMyCanvasextendsCanvas
{
Colorc;
MyCanvas(Colorc)
{setSize(20,20);
this.c=c;
}
publicvoidpaint(Graphicsg)
{g.setColor(c);
g.fillOval(0,0,20,20);
}
}
例子12
importjava.awt.event.;
importjava.awt.;
importjava.util.Date;
publicclassExample9_12
{publicstaticvoidmain(Stringargs[])
{newWin();
}
}
classWinextendsFrame
implementsRunnable,ActionListener
{Threadthread=null;
TextAreatext=null;
ButtonbuttonStart=newButton("Start"),
buttonStop=newButton("Stop");
booleandie;
Win()
{thread=newThread(this);
text=newTextArea();
add(text,BorderLayout.CENTER);
Panelp=newPanel();
p.add(buttonStart);
p.add(buttonStop);
buttonStart.addActionListener(this);
buttonStop.addActionListener(this);
add(p,BorderLayout.NORTH);
setVisible(true);
setSize(500,500);
validate();
addWindowListener(newWindowAdapter()
{publicvoidwindowClosing(WindowEvente)
{System.exit(0);
}
});
}
publicvoidactionPerformed(ActionEvente)
{if(e.getSource()==buttonStart)
{if(!(thread.isAlive()))
{thread=newThread(this);
die=false;
}
try{thread.start();
}
catch(Exceptione1)
{text.setText("线程没有结束run方法之前,不要再调用start方法");
}
}
elseif(e.getSource()==buttonStop)
{die=true;
}
}
publicvoidrun()
{while(true)
{text.append("\n"+newDate());
try{thread.sleep(1000);
}
catch(InterruptedExceptionee){}
if(die==true)
return;
}
}
}
例子13
importjava.awt.;
importjava.awt.event.;
publicclassExample9_13
{publicstaticvoidmain(Stringargs[])
{newFrameMoney();
}
}
classFrameMoneyextendsFrame
implementsRunnable,ActionListener
{intmoney=100;
TextAreatext1,text2;
Thread会计,出纳;
intweekDay;
Buttonstart=newButton("开始演示");
FrameMoney()
{会计=newThread(this);
出纳=newThread(this);
text1=newTextArea(12,15);
text2=newTextArea(12,15);
setLayout(newFlowLayout());
add(start);
add(text1);
add(text2);
setVisible(true);
setSize(360,300);
validate();
addWindowListener(newWindowAdapter()
{publicvoidwindowClosing(WindowEvente)
{System.exit(0);
}
});
start.addActionListener(this);
}
publicvoidactionPerformed(ActionEvente)
{if(!(出纳.isAlive()))
{会计=newThread(this);
出纳=newThread(this);
}
try
{会计.start();
出纳.start();
}
catch(Exceptionexp){}
}
publicsynchronizedvoid存取(intnumber)//存取方法
{if(Thread.currentThread()==会计)
{text1.append("今天是星期"+weekDay+"\n");
for(inti=1;i<=3;i++)//会计使用存取方法存入90元,存入30元,稍歇一下
{money=money+number;//这时出纳仍不能使用存取方法
try{Thread.sleep(1000);//因为会计还没使用完存取方法
}
catch(InterruptedExceptione){}
text1.append("帐上有"+money+"万\n");
}
}
elseif(Thread.currentThread()==出纳)
{text2.append("今天是星期"+weekDay+"\n");
for(inti=1;i<=2;i++)//出纳使用存取方法取出30元,取出15元,稍歇一下
{money=money-number/2;//这时会计仍不能使用存取方法
try{Thread.sleep(1000);//因为出纳还没使用完存取方法
}
catch(InterruptedExceptione){}
text2.append("帐上有"+money+"万\n");
}
}
}
publicvoidrun()
{if(Thread.currentThread()==会计||Thread.currentThread()==出纳)
{for(inti=1;i<=3;i++)//从周一到周三会计和出纳都要使用帐本
{weekDay=i;
存取(30);
}
}
}
}
例子14
importjava.awt.;
importjava.awt.event.;
publicclassExample9_14
{publicstaticvoidmain(Stringargs[])
{newMyFrame();
}
}
classMyFrameextendsFrame
implementsRunnable,ActionListener
{售票员王小姐;
Thread张平,李明;
staticTextAreatext;
Buttonstart=newButton("排队买票");
MyFrame()
{王小姐=new售票员();
张平=newThread(this);
李明=newThread(this);
text=newTextArea(10,30);
start.addActionListener(this);
add(text,BorderLayout.CENTER);
add(start,BorderLayout.NORTH);
setVisible(true);
setSize(360,300);
validate();
addWindowListener(newWindowAdapter()
{publicvoidwindowClosing(WindowEvente)
{System.exit(0);
}
});
}
publicvoidactionPerformed(ActionEvente)
{try{张平.start();
李明.start();
}
catch(Exceptionexp){}
}
publicvoidrun()
{if(Thread.currentThread()==张平)
{王小姐.售票规则(20);
}
elseif(Thread.currentThread()==李明)
{王小姐.售票规则(5);
}
}
}
class售票员
{int五元钱的个数=2,十元钱的个数=0,二十元钱的个数=0;
Strings=null;
publicsynchronizedvoid售票规则(intmoney)
{if(money==5)//如果使用该方法的线程传递的参数是5,就不用等待
{五元钱的个数=五元钱的个数+1;
s="给您入场卷您的钱正好";
MyFrame.text.append("\n"+s);
}
elseif(money==20)
{while(五元钱的个数<3)
{try{wait();//如果使用该方法的线程传递的参数是20须等待
}
catch(InterruptedExceptione){}
}
五元钱的个数=五元钱的个数-3;
二十元钱的个数=二十元钱的个数+1;
s="给您入场卷"+"您给我20,找您15元";
MyFrame.text.append("\n"+s);
}
notifyAll();
}
}
例子15
classAimplementsRunnable
{inti=0;
Stringname;
publicvoidrun()
{while(true)
{i++;
System.out.println(name+"i="+i);
if(i==5)
{try{挂起线程();
}
catch(Exceptione){}
}
try{Thread.sleep(1000);
}
catch(Exceptione){}
}
}
publicsynchronizedvoid挂起线程()throwsInterruptedException
{wait();
}
publicsynchronizedvoid恢复线程()
{notifyAll();
}
}
publicclassExample9_15
{publicstaticvoidmain(Stringargs[])
{intm=0;
Atarget=newA();//线程的目标对象
target.name="张三";
Threadthread=newThread(target);
thread.setName(target.name);
thread.start();
while(true)
{m++;
System.out.println("我是主线程m="+m);
if(m==20)
{System.out.println("让"+thread.getName()+"继续工作");
try{target.恢复线程();//主线程占有CPU资源期间
}//让thread的目标对象调用notifyAll()
catch(Exceptione){}
break;
}
try{Thread.sleep(1000);
}
catch(Exceptione){}
}
}
}
例子16
classMyThreadextendsThread
{inti=0;
publicvoidrun()
{while(true)
{i++;
System.out.println("我的名字是"+getName()+"i="+i);
if(i==10)
{try{挂起线程();
}
catch(Exceptione){}
}
try{Thread.sleep(1000);
}
catch(Exceptione){}
}
}
publicsynchronizedvoid挂起线程()throwsInterruptedException
{wait();
}
publicsynchronizedvoid恢复线程()
{notifyAll();
}
}
classYourThreadextendsThread
{intm=0;
MyThreadotherThread;
YourThread(MyThreada)
{otherThread=a;
}
publicvoidrun()
{while(true)
{m++;
System.out.println("我的名字是"+getName()+"m="+m);
if(m==20)
{System.out.println("恢复线程:"+otherThread.getName());
System.out.println(getName()+"停止工作");
try{otherThread.恢复线程();
}
catch(Exceptione){}
return;
}
try{Thread.sleep(1000);
}
catch(Exceptione){}
}
}
}
publicclassExample9_16
{publicstaticvoidmain(Stringargs[])
{MyThreadthread1=newMyThread();
thread1.setName("张三");
thread1.start();
YourThreadthread2=newYourThread(thread1);
thread2.setName("李四");
thread2.start();
}
}
例子17
importjava.awt.;
importjava.awt.event.;
publicclassExample9_17
{publicstaticvoidmain(Stringargs[])
{Winwin=newWin();
}
}
classWinextendsFrameimplements
Runnable,ActionListener
{ThreadmoveOrStop;
Button开始,挂起,恢复,终止;
LabelmoveLabel;
booleanmove=false,die=false;
Win()
{moveOrStop=newThread(this);
开始=newButton("线程开始");
挂起=newButton("线程挂起");
恢复=newButton("线程恢复");
终止=newButton("线程终止");
开始.addActionListener(this);
挂起.addActionListener(this);
恢复.addActionListener(this);
终止.addActionListener(this);
moveLabel=newLabel("线程负责运动我");
moveLabel.setBackground(Color.cyan);
setLayout(newFlowLayout());
add(开始);add(挂起);
add(恢复);add(终止);
add(moveLabel);
setSize(200,300);
validate();
setVisible(true);
addWindowListener(newWindowAdapter()
{publicvoidwindowClosing(WindowEvente)
{System.exit(0);
}
});
}
publicvoidactionPerformed(ActionEvente)
{if(e.getSource()==开始)
{try{move=true;
moveOrStop.start();
}
catch(Exceptionevent){}
}
elseif(e.getSource()==挂起)
{move=false;
}
elseif(e.getSource()==恢复)
{move=true;
恢复线程();
}
elseif(e.getSource()==终止)
{die=true;
}
}
publicvoidrun()
{while(true)
{
while(!move)//如果move是false,挂起线程。
{try{挂起线程();
}
catch(InterruptedExceptione1){}
}
intx=moveLabel.getBounds().x;
inty=moveLabel.getBounds().y;
y=y+2;
if(y>=200)y=10;
moveLabel.setLocation(x,y);
try{moveOrStop.sleep(200);
}
catch(InterruptedExceptione2){}
if(die==true)
{return;//终止线程。
}
}
}
publicsynchronizedvoid挂起线程()throwsInterruptedException
{wait();
}
publicsynchronizedvoid恢复线程()
{notifyAll();
}
}
例子18
importjava.awt.;
importjava.awt.event.;
importjavax.swing.Timer;
publicclassExample9_18
{publicstaticvoidmain(Stringargs[])
{TimeWinWin=newTimeWin();
}
}
classTimeWinextendsFrameimplementsActionListener
{TextFieldtext;
ButtonbStart,bStop,bContinue;
Timertime;
intn=0,start=1;
TimeWin()
{time=newTimer(1000,this);//TimeWin对象做计时器的监视器。
text=newTextField(10);
bStart=newButton("开始计时");
bStop=newButton("暂停计时");
bContinue=newButton("继续计时");
bStart.addActionListener(this);
bStop.addActionListener(this);
bContinue.addActionListener(this);
setLayout(newFlowLayout());
add(bStart);
add(bStop);
add(bContinue);
add(text);
setSize(500,500);
validate();
setVisible(true);
addWindowListener(newWindowAdapter()
{publicvoidwindowClosing(WindowEvente)
{System.exit(0);
}
});
}
publicvoidactionPerformed(ActionEvente)
{if(e.getSource()==time)
{java.util.Datedate=newjava.util.Date();
Stringstr=date.toString().substring(11,19);
text.setText("时间:"+str);
intx=text.getBounds().x;
inty=text.getBounds().y;
y=y+2;
text.setLocation(x,y);
}
elseif(e.getSource()==bStart)
{time.start();
}
elseif(e.getSource()==bStop)
{time.stop();
}
elseif(e.getSource()==bContinue)
{time.restart();
}
}
}
例子19
publicclassExample9_19
{publicstaticvoidmain(Stringargs[])
{ThreadJoina=newThreadJoin();
a.customer.start();
a.tvMaker.start();
}
}
classThreadJoinimplementsRunnable
{TVtv;
Threadcustomer,tvMaker;
ThreadJoin()
{customer=newThread(this);
tvMaker=newThread(this);
customer.setName("顾客");
tvMaker.setName("电视制造厂");
}
publicvoidrun()
{if(Thread.currentThread()==customer)
{
System.out.println(customer.getName()+"等"+tvMaker.getName()+"生产电视");
try{tvMaker.join();//线程customer开始等待tvMaker结束
}
catch(InterruptedExceptione){}
System.out.println(customer.getName()+
"买了一台电视:"+tv.name+"价钱:"+tv.price);
}
elseif(Thread.currentThread()==tvMaker)
{System.out.println(tvMaker.getName()+"开始生产电视,请等...");
try{tvMaker.sleep(2000);
}
catch(InterruptedExceptione){}
tv=newTV("红星牌",3288);
System.out.println(tvMaker.getName()+"生产完毕");
}
}
}
classTV
{floatprice;
Stringname;
TV(Stringname,floatprice)
{this.name=name;
this.price=price;
}
}
例子20
publicclassExample9_20
{publicstaticvoidmain(Stringargs[])
{Daemona=newDaemon();
a.A.start();
a.B.setDaemon(true);
a.B.start();
}
}
classDaemonimplementsRunnable
{ThreadA,B;
Daemon()
{A=newThread(this);
B=newThread(this);
}
publicvoidrun()
{if(Thread.currentThread()==A)
{for(inti=0;i<8;i++)
{System.out.println("i="+i);
try{Thread.sleep(1000);
}
catch(InterruptedExceptione){}
}
}
elseif(Thread.currentThread()==B)
{while(true)
{System.out.println("线程B是守护线程");
try{Thread.sleep(1000);
}
catch(InterruptedExceptione){}
}
}
}
}
|
|