第九章JAVA线程Word文档格式.docx
《第九章JAVA线程Word文档格式.docx》由会员分享,可在线阅读,更多相关《第九章JAVA线程Word文档格式.docx(20页珍藏版)》请在冰豆网上搜索。
}
}
}
classRunner1implementsRunnable{
publicvoidrun(){
i++){
Runner1:
"
//**************************************************************
r.start();
classRunner1extendsThread{
推荐使用接口创建线程
thread.interrupt();
//中断睡眠,让子线程结束
thread.stop();
//中断线程,最粗暴的中断线程的方法
importjava.util.*;
publicclassTestInterrupt{
publicstaticvoidmain(String[]args){
MyThreadthread=newMyThread();
thread.start();
try{Thread.sleep(10000);
catch(InterruptedExceptione){}
thread.interrupt();
classMyThreadextendsThread{
booleanflag=true;
publicvoidrun(){
while(flag){
System.out.println("
==="
+newDate()+"
);
try{
sleep(1000);
}catch(InterruptedExceptione){
return;
/*
publicvoidrun(){
while(true){
Stringtemp=newDate().toString();
Stringt=temp.substring(11,temp.indexOf('
C'
));
t=t.trim();
String[]time=t.split("
:
if(time.length==3){
System.out.println(“现在是”+time[0]+“点”+
time[1]+"
分"
+time[2]+"
秒"
Thread.sleep(5000);
}
*/
publicclassTestJoin{
MyThread2t1=newMyThread2("
abcde"
t1.start();
t1.join();
}catch(InterruptedExceptione){}
for(inti=1;
i<
=10;
i++){
iammainthread"
classMyThread2extendsThread{
MyThread2(Strings){
super(s);
for(inti=1;
iam"
+getName());
sleep(1000);
return;
publicclassTestYield{
MyThread3t1=newMyThread3("
t1"
MyThread3t2=newMyThread3("
t2"
t2.start();
classMyThread3extendsThread{
MyThread3(Strings){super(s);
=100;
System.out.println(getName()+"
"
+i);
if(i%10==0){
yield();
publicclassTestPriority{
Threadt1=newThread(newT1());
Threadt2=newThread(newT2());
t1.setPriority(Thread.NORM_PRIORITY+3);
t1.start();
t2.start();
classT1implementsRunnable{
1000;
T1:
classT2implementsRunnable{
------T2:
正确停止线程的方法
publicclassTestThread4{
publicstaticvoidmain(Stringargs[]){
Runner4r=newRunner4();
t.start();
for(inti=0;
100000;
if(i%10000==0&
i>
0)
inthreadmaini="
Threadmainisover"
r.shutDown();
//t.stop();
classRunner4implementsRunnable{
privatebooleanflag=true;
inti=0;
while(flag==true){
System.out.print("
+i++);
publicvoidshutDown(){
flag=false;
publicclassTestSyncimplementsRunnable{
Timertimer=newTimer();
TestSynctest=newTestSync();
Threadt1=newThread(test);
Threadt2=newThread(test);
t1.setName("
t2.setName("
timer.add(Thread.currentThread().getName());
classTimer{
privatestaticintnum=0;
publicsynchronizedvoidadd(Stringname){
//synchronized(this){
num++;
try{Thread.sleep
(1);
}
System.out.println(name+"
你是第"
+num+"
个使用timer的线程"
//}
线程死锁例子,视频线程同步4集
publicclassTestDeadLockimplementsRunnable{
publicintflag=1;
staticObjecto1=newObject(),o2=newObject();
System.out.println("
flag="
+flag);
if(flag==1){
synchronized(o1){
try{
Thread.sleep(500);
}catch(Exceptione){
e.printStackTrace();
}
synchronized(o2){
System.out.println("
1"
}
if(flag==0){
synchronized(o2){
synchronized(o1)