第十五章 Java多线程机制_第1页
第十五章 Java多线程机制_第2页
第十五章 Java多线程机制_第3页
第十五章 Java多线程机制_第4页
第十五章 Java多线程机制_第5页
已阅读5页,还剩20页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

本章内容❏

线程的基本概念❏

线程的创建和启动❏

线程的调度和优先级❏

线程的状态控制❏

线程的应用线程的基本概念线程是一个程序内部的顺序控制流。线程和进程的区别每个进程都有独立的代码和数据空间(进程上下文),进程间的切换会有较大的开销。线程可以看成时轻量级的进程,同一类线程共享代码和数据空间,每个线程有独立的运行栈和程序计数器(PC),线程切换的开销小。多进程:在操作系统中能同时运行多个任务(程序)多线程:在同一应用程序中有多个顺序流同时执行线程的基本概念Java的线程是通过java.lang.Thread类来实现的。VM

启动时会有一个由主方法(public

staticvoid

main(){})所定义的线程。可以通过创建Thread

的实例来创建新的线程。每个线程都是通过某个特定Thread对象所对应的方法run()来完成其操作的,方法run()称为线程体。通过调用Thead类的start()方法来启动一个线程。线程的创建和启动可以有两种方式创建新的线程。ThreadmyThread

=newThead(target)其中target为java.lang.Runnable接口类型。

Runnable中只有一个方法:public

void

run();用以定义线程运行体。可以定义一个Thread的子类并重写其run方法如:class

MyThread

extends

Thead

{public

void

run(){…}}然后生成该类的对象:MyThread

myThread=new

MyThead(…)线程的创建和启动举例public

class

Test

{publicstatic

void

main(String[]

args)

{MyThread

thread1

=

new

MyThread("thread1");MyThread

thread2

=

new

MyThread("thread2");MyThread

thread3

=

new

MyThread("thread3");thread1.start();

thread2.start();thread3.start();}}class

MyThread

extends

Thread

{MyThread(String

name){super(name);}public

void

run(){for(int

i

=1;i<=1000;i++){System.out.println("i

am

"+getName()+".");}}}线程的创建和启动举例public

class

Test

{publicstatic

void

main(String[]

args)

{Thread

thread1

=

new

Thread(new

Runner("thread1"));Thread

thread2

=

new

Thread(new

Runner("thread2"));Thread

thread3

=

new

Thread(new

Runner("thread3"));thread1.start();

thread2.start();thread3.start();}}class

Runner

implements

Runnable

{private

String

name;Runner(String

name){

=

name;}public

void

run(){for(int

i

=1;i<=1000;i++){System.out.println("i

am

"+name+".");}}}课堂练习分别使用两种方法创建一个线程,在屏幕上打印出1~20的阶乘。import

java.util.*;public

class

Test

{public

static

void

main(String[]

args)

{MyThread

addThread

=new

MyThread("addThread",MyThread.ADD);MyThread

subThread

=new

MyThread("subThread",MyThread.SUB);MyThread

mulThread

=new

MyThread("mulThread",MyThread.MUL);addThread.start();subThread.start();mulThread.start();}}线程的创建举例1class

MyThread

extends

Thread

{public

static

final

int

ADD

=

1;public

static

final

int

SUB

=

2;public

static

final

int

MUL

=

3;private

int

operator

=

ADD;privateString

threadName

=

null;MyThread(String

name,

int

op)

{super(name);

operator

=

op;}public

voidrun(){Random

random

=

new

Random();for

(int

i

=

1;

i

<=

1000;

i++)

{int

x

=

random.nextInt(100);

int

y

=

random.nextInt(100);

switch

(operator)

{case

ADD

:System.out.println(getName()

+

":

"+x+"+"+y+"="+(x

+

y));

break;case

SUB

:System.out.println(getName()

+

":"

+x+"-"+y+"="+(x

-

y));

break;case

MUL

:

System.out.println(getName()

+

":

"+x+"*"+y+"="+(x

*

y));

break;default

:

System.out.println("Can"t

support");}}}}线程的创建举例1(续)课堂练习使用Runnable接口的方法,实现上面的例子。使用Runnable在实现Runnable接口的类的run方法定义中可以使用

Thread的静态方法:public

static

Thread

currentThread()获取当前线程的引用。Runnable举例public

class

Test

{publicstatic

void

main(String[]

args)

{String[]

p

=

{"Mircosoft","IBM","Sun","Apple","HP"};Products

products

=

new

Products(p);Thread

upper

=

new

Thread(products,"upper");Thread

lower

=

new

Thread(products,"lower");upper.start();

lower.start();}}class

Products

implements

Runnable

{String[]

p;Products(String[]

p){this.p

=

p;}public

void

run(){String

name

=

Thread.currentThread().getName();if(name.equals("upper")){for(int

i=0;i<p.length;i++){System.out.println(p[i].toUpperCase());}}else

if(name.equals("lower")){for(int

i=0;i<p.length;i++){System.out.println(p[i].toLowerCase());}}}}线程状态转换方法功

能isAlive()判断线程是否还“活”着,即线程是否还未终止。getPriority()获得线程的优先级数值setPriority()设置线程的优先级数值Thread.sleep()将当前线程睡眠指定毫秒数join()调用某线程的该方法,将当前线程与该线程“合并”,即等待该线程结束,再恢复当前线程的运行。yield()让出CPU,当前线程进入就绪队列等待调度。wait()当前线程进入对象的wait

pool。notify()/notifyAll()唤醒对象的wait

pool中的一个/所有等待线程。线程控制基本方法线程的优先级别Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程。线程调度器按照线程的优先级决定应调度哪个线程来执行。线程的优先级用数字来表示,范围从1到10,一个线程的缺省优先级是5。Thread.MIN_PRIORITY

=

1Thread.MAX_PRIORITY

=

10Thread.NORM_PRIORITY

=

5使用下述线方法获得或设置线程对象的优先级。int

getPriority();void

setPriority(int

newPriority);import

java.awt.*;public

class

Test

{public

static

voidmain(String[]

args)

{Frame

f

=

new

Frame("thread");f.setLayout(null);f.setBounds(300,60,300,200);

f.setVisible(true);f.add(new

MyTextArea(150,0,Thread.MIN_PRIORITY));f.add(new

MyTextArea(0,0,Thread.MAX_PRIORITY));}}class

MyTextArea

extends

TextArea

implements

Runnable{MyTextArea(int

x,

int

y,

int

priority){setForeground(Color.BLUE);setSize(150,200);

setLocation(x,y);Thread

writer

=

new

Thread(this);writer.setPriority(priority);writer.start();}publicvoidrun(){for(int

i

=

1;i<=5000;i++){append(i+"\n");}}}线程的优先级别举例sleep方法可以调用Thread的静态方法:public

static

void

sleep(long

millis)throws

InterruptedException使得当前线程休眠(暂时停止执行millis毫秒)。Thread定义有方法:public

void

interrupt()interrupt()方法不会中断一个正在运行的线程。这一方法实际完成的是:在线程受到阻塞时抛出一个中断信号,这样线程就得以退出阻塞的状态。更确切的说,如果线程被Object.wait,Thread.join和Thread.sleep三种方法之一阻塞,那么,它将接收到一个中断异常(InterruptedException),从而提

地终结被阻塞状态。如果线程被上述几种方法阻塞,正确的停止线程方式是设置共享变量,并调用interrupt()(注意变量应该先设置)。如果线程没有被阻塞,这时调用interrupt()将不起作用;否则,线程就将得到异常,接着

逃离阻塞状态。sleep方法举例-1import

java.util.*;public

class

Test

{publicstatic

void

main(String[]

args)

{MyThread

thread

=

new

MyThread();thread.start();try

{Thread.sleep(10000);}catch

(InterruptedException

e)

{e.printStackTrace();}errupt();}}class

MyThread

extends

Thread

{public

void

run(){while(true){System.out.println("==="+new

Date()+"===");try

{sleep(1000);}

catch

(InterruptedException

e)

{return;}}}}sleep方法举例-2import

java.util.*;public

class

Test

{publicstatic

void

main(String[]

args)

{Thread

thread

=

new

Thread(new

Runnable()

{public

void

run()

{while

(true)

{System.out.println("==="+

new

Date()

+

"===");try

{Thread.sleep(1000);}catch

(InterruptedException

e)

{return;}}}});thread.start();try

{Thread.sleep(10000);}

catch

(InterruptedException

e)

{}errupt();}}import

java.io.*;

import

java.util.*;public

class

Test

implements

Runnable

{public

static

void

main(String[]

args)

{BufferedReader

br

=new

BufferedReader(new

InputStreamReader(System.in));Test

test

=

new

Test();

Thread

timer

=

new

Thread(test);Random

random

=

new

Random();timer.start();

int

correct

=

0;for(int

i

=

1;i<=10;i++){int

d1

=

random.nextInt(100),

d2

=

random.nextInt(100);System.out.println(d1+"+"+d2+"

=

?");

String

result

=

null;try

{while((result=br.readLine())!=null){try

{if(Integer.parseInt(result)==d1+d2){System.out.println("ok!!!");

correct++;

break;}}

catch

(NumberFormatException

e)

{break;}}}

catch

(IOException

e)

{e.printStackTrace();}}System.out.println("共答对"+correct+"道题目");

errupt();}线程举例-1…

…public

void

run()

{while

(true)

{String

temp

=

new

Date().toString();String

t

=

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]+"秒");}try

{Thread.sleep(5000);}

catch

(InterruptedException

e)

{return;}}}}线程举例-1(续)import

java.awt.*;public

class

Test{publicstatic

void

main(String[]

args)

{MyFrame

myFrame

=

new

MyFrame();}}class

MyFrame

extends

Frame

implements

Runnable{private

Thread

runner1,runner2;privatePointpoint1,point2;MyFrame(){super("runing...");setLayout(null);

setBounds(200,60,600,500);setBackground(Color.BLACK);setVisible(true);runner1

=

new

Thread(this);

point1

=

new

Point(0,0);runner2

=

new

Thread(this);

point2

=

new

Point(300,0);runner1.start();

runner2.start();}…

…线程举例-2public

void

paint(Graphics

g){g.setColor(Color.RED);g.fillOval(point1.x,point2.y,20,20);g.setColor(Color.YELLOW);g.fillOval(point2.x,point2.y,20,20);g.setColor(Color.GREEN);g.drawString(point1.x+","+point1.y,point1.x,point1.y);g.drawString(point2.x+","+point2.y,point2.x,point2.y);}public

void

run(){for(int

t=0;t<=95;t++){if(Thread.currentThread()==runner1){point1.x

=

20*t/10;

point1.y=(int)(0.5*9.8*t*t/100);}else

if(Thread.currentThread()==runner2){point2.y

=

(int)(0.5*9.8*t*t/100);}repai

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论