《Java编程那点事儿》读书笔记(七)——多线程
1.继承Thread类
通过编写新的类继承Thread类可以实现多线程,其中线程的代码必须书写在run方法内部或者在run方法内部进行调用。
public class NewThread extends Thread {
private int ThreadNum; public NewThread(int ThreadNum){
this.ThreadNum = ThreadNum;
} public void run(){
try{
for(int i = 0;i < 10;i ++){
Thread.sleep(1000);
System.out.println("running Thread"+ThreadNum+":"+i);
}
}catch(Exception e){ }
}
}
上述代码定义了新线程NewThread,并在run中实现输出十个数的功能。用以下代码在main函数中调用:
NewThread nt = new NewThread(1);
nt.start(); NewThread nt2 = new NewThread(2);
nt2.start();
得到的结果如下:
running Thread1:0
running Thread2:0
running Thread1:1
running Thread2:1
running Thread1:2
running Thread2:2
running Thread1:3
running Thread2:3
running Thread1:4
running Thread2:4
running Thread1:5
running Thread2:5
running Thread1:6
running Thread2:6
running Thread1:7
running Thread2:7
running Thread1:8
running Thread2:8
running Thread1:9
running Thread2:9
可以看到启动的两个线程并行运行。
2.实现Runnable接口(Java.lang.Runnable)
public class MyRunnable implements Runnable {
private int ThreadNum; public MyRunnable(int ThreadNum){
this.ThreadNum = ThreadNum;
}
public void run(){
try{
for(int i = 0;i < 10;i ++){
Thread.sleep(1000);
System.out.println("running Thread"+ThreadNum+":"+i);
}
}catch(Exception e){ }
}
}
在main中调用接口:
MyRunnable mr = new MyRunnable(1);
Thread t = new Thread(mr); MyRunnable mr2 = new MyRunnable(2);
Thread t2 = new Thread(mr2); t.start();
t2.start();
3.Timer & TimerTask组合实现多线程
public class TimerAndTimerTask extends TimerTask{
private String s;
public TimerAndTimerTask(String s){
this.s = s;
} public void run(){
try{
for(int i = 0;i < 10;i ++){
Thread.sleep(1000);
System.out.println("running Thread"+s+":"+i);
}
}catch(Exception e){ }
}
}
在main函数中创建线程代码如下:
Timer t = new Timer();
Timer t2 = new Timer(); TimerAndTimerTask tatt = new TimerAndTimerTask("1");
TimerAndTimerTask tatt2 = new TimerAndTimerTask("2"); t.schedule(tatt, 0);
t2.schedule(tatt2, 0);
上述代码中的要用两个Timer启动不同的线程,它们才能同时运行。如果只用一个Timer,则一次只能启动一个线程。
上述中的schedule方法一共有四种多态:
public void schedule(TimeTask task, Date time) //在2009年10月1日10点0分0秒启动该线程或超过该时间也启动线程
Date d = new Date(2009-1900,10-1,1,10,0,0);
t.schedule(task,d);
public void schedule(TimerTask task,Date firstTime,long period) //到达或者超过2009年10月1日10点时候每隔20000ms就启动一次线程,这种方式会重复触发线程
Date d = new Date(2009-1900,10-1,1,10,0,0);
t.schedule(task,d,20000);
public void schedule(TimerTask task,long delay) //执行启动代码1000ms后启动线程
t.schedule(task,1000);
//在delay ms后启动线程,并且每隔period ms启动一次
public void schedule(TimerTask task,long delay,long period)
在eclipse里面试了一下最后一种,会不断的输出0~9这10个数,因为用的Timer只有一个,但是每过1s就触发一次线程,所以不停的有线程需要执行。
4.互斥
synchronized,修饰方法或代码块,表示如果两个或者以上的线程同时执行该代码段时,如果一个线程已经开始执行该代码段,则另外一个线程必须等待这个线程执行完这段代码后才能执行。
public class Toilet {
public synchronized void enter(String name){
System.out.println(name+" enters the toilet!");
try{
Thread.sleep(2000);
}catch(Exception e){}
System.out.println(name + " has left the toilet!");
}
} public class Human extends Thread{
private Toilet t;
private String s;
public Human(String s,Toilet t){
this.s = s;
this.t = t;
start();
} public void run(){
t.enter(s);
}
}
在main中创建Human线程的代码如下,一共创建了三个Human线程:
Toilet t = new Toilet();
Human t1 = new Human("Ann", t);
Human t2 = new Human("Jeff", t);
Human t3 = new Human("Joe", t);
在上述Toilet类中有一段互斥的代码,输出当前进入厕所的人,并且在1s后离开。
在类Human中,在构造函数里面开启进程,所以每当new一个Human类就相当于开启了一个线程,但是会不会立即执行run函数要看系统中是否已经有在跑的Human线程,因为run函数里面调用了Toilet类中的enter函数,这个函数是互斥的,一次只能有一个线程执行。
程序两次执行的结果如下:
Jeff enters the toilet!
Jeff has left the toilet!
Joe enters the toilet!
Joe has left the toilet!
Ann enters the toilet!
Ann has left the toilet!
Ann enters the toilet!
Ann has left the toilet!
Jeff enters the toilet!
Jeff has left the toilet!
Joe enters the toilet!
Joe has left the toilet!
可以看到,线程执行的顺序并不是固定的,但是同一时刻一定只有一个线程可以执行enter这段代码。
5.同步
主要涉及两个函数
wait():使调用该方法的线程进入休眠
notify():使调用该方法的线程被唤醒
6.线程优先级
MAX_PRIORITY //最高优先级
NORM_PRIORITY //普通(默认)优先级
MIN_PRIORITY //最低优先级
如果上述main函数中通过调用MyRunnable类实现多线程的main函数中的程序改为如下:
MyRunnable mr = new MyRunnable(1);
Thread t = new Thread(mr);
t.setPriority(Thread.MIN_PRIORITY); MyRunnable mr2 = new MyRunnable(2);
Thread t2 = new Thread(mr2);
t2.setPriority(Thread.NORM_PRIORITY); MyRunnable mr3 = new MyRunnable(3);
Thread t3 = new Thread(mr3);
t3.setPriority(Thread.MAX_PRIORITY); t.start();
t2.start();
t3.start();
但是我没有得到书上的结果,大部分情况下是线程3先执行,但有时候也会出现线程2先执行的情况,某次执行的结果如下:
running Thread3:0
running Thread1:0
running Thread2:0
running Thread3:1
running Thread2:1
running Thread1:1
running Thread3:2
running Thread1:2
running Thread2:2
running Thread3:3
running Thread1:3
running Thread2:3
running Thread3:4
running Thread1:4
running Thread2:4
running Thread3:5
running Thread1:5
running Thread2:5
running Thread3:6
running Thread1:6
running Thread2:6
running Thread3:7
running Thread1:7
running Thread2:7
running Thread3:8
running Thread1:8
running Thread2:8
running Thread3:9
running Thread1:9
running Thread2:9
《Java编程那点事儿》读书笔记(七)——多线程的更多相关文章
- 《Java并发编程的艺术》读书笔记:二、Java并发机制的底层实现原理
二.Java并发机制底层实现原理 这里是我的<Java并发编程的艺术>读书笔记的第二篇,对前文有兴趣的朋友可以去这里看第一篇:一.并发编程的目的与挑战 有兴趣讨论的朋友可以给我留言! 1. ...
- 《深入了解java虚拟机》高效并发读书笔记——Java内存模型,线程,线程安全 与锁优化
<深入了解java虚拟机>高效并发读书笔记--Java内存模型,线程,线程安全 与锁优化 本文主要参考<深入了解java虚拟机>高效并发章节 关于锁升级,偏向锁,轻量级锁参考& ...
- <<Java RESTful Web Service实战>> 读书笔记
<<Java RESTful Web Service实战>> 读书笔记 第一章 JAX-RS2.0入门 REST (Representational State ransf ...
- 《Java并发编程的艺术》读书笔记:一、并发编程的目的与挑战
发现自己有很多读书笔记了,但是一直都是自己闷头背,没有输出,突然想起还有博客圆这么个好平台给我留着位置,可不能荒废了. 此文读的书是<Jvava并发编程的艺术>,方腾飞等著,非常经典的一本 ...
- 《Effective Java中文版第二版》读书笔记
说明 这里是阅读<Effective Java中文版第二版>的读书笔记,这里会记录一些个人感觉稍微有些重要的内容,方便以后查阅,可能会因为个人实力原因导致理解有误,若有发现欢迎指出.一些个 ...
- 《深入分析Java Web技术内幕》读书笔记之JVM内存管理
今天看JVM的过程中收获颇丰,但一想到这些学习心得将来可能被遗忘,便一阵恐慌,自觉得以后要开始坚持做读书笔记了. 操作系统层面的内存管理 物理内存是一切内存管理的基础,Java中使用的内存和应用程序的 ...
- MDX Step by Step 读书笔记(七) - Performing Aggregation 聚合函数之 Max, Min, Count , DistinctCount 以及其它 TopCount, Generate
MDX 中最大值和最小值 MDX 中最大值和最小值函数的语法和之前看到的 Sum 以及 Aggregate 等聚合函数基本上是一样的: Max( {Set} [, Expression]) Min( ...
- 《Java编程那点事儿》读书笔记(一)——基本数据结构
觉得自己记忆力很烂的样子,读书不做笔记就好像没读一样,所以决定以后读技术类的书籍,都要做好笔记. 1.IP地址和域名:如果把IP地址类比成身份证号的话,域名就是持证人的名字. 2.端口:规定一个 设备 ...
- 《Java编程那点事儿》读书笔记(五)——System,Integer,Calendar,Random和容器
System 1)arraycopy int[] a = {1.2.3.4}; int[] b = new int[5]; System.arraycopy(a,1,b,3,2); //把数组a中从下 ...
随机推荐
- 随机产生30个两个两位数相加的题目(java)
编程思路: 1首先遇到JAVA产生随机数的问题. 2把产生的随机数设定范围. 3把划分的范围再分四个小区段分别对应四则运算法则加减乘除. 4打印输出. 题目源代码(Java) package coun ...
- Segment Tree 扫描线 分类: ACM TYPE 2014-08-29 13:08 89人阅读 评论(0) 收藏
#include<iostream> #include<cstdio> #include<algorithm> #define Max 1005 using nam ...
- Phyre LCUE with YEBIS cause issues about GS
when LCUE enabled in phyreEngine when Yebis integrated and render there are two mainloopdraws in one ...
- HBAO
nv算是坑死我了,之前下的hbao的sample这次怎么都找不到 http://developer.download.nvidia.com/SDK/10.5/direct3d/samples.html ...
- 常量折叠 const folding
http://bbs.byr.cn/#!article/CPP/86336?p=1 下列代码给出输出结果: #include"stdafx.h" #include <iost ...
- 异步任务(AsyncTask)
1.Android UI组件更新简介 Android的UI线程主要负责处理用户的按键事件.用户触屏事件及屏幕绘图事件等,因此开发者的其它操作不应该,也不能阻塞UI线程,否则UI界面将会变的停止响应.A ...
- BZOJ 1088
真是智商不够, 智商题:.... 假如:第1,2个格子已知,然后根据第二列的情况,就可以把所有满足的情况推出来,又萌萌哒.. 无耻攒字数: #include<stdio.h> using ...
- 【转】CSS实现div的高度填满剩余空间
转自:http://www.cnblogs.com/zhujl/archive/2012/03/20/2408976.html 高度自适应问题,我很抵触用js去解决,因为不好维护,也不够自然,但是纯用 ...
- 通过登入IP记录Linux所有用户登录所操作的日志
通过登入IP记录Linux所有用户登录所操作的日志 对于Linux用户操作记录一般通过命令history来查看历史记录,但是如果在由于误操作而删除了重要的数据的情况下,history命令就不会有什么作 ...
- php laravel 安装
windows环境尝试学习一下laravel 1.因为SAE的php版本为5.3,因此最高只能支持到Laravel4.1.x.(Laravel4.2用到了php5.4的trait特性) 以4.1为主. ...