《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中从下 ...
随机推荐
- JS 学习笔记--9---变量-作用域-内存相关
JS 中变量和其它语言中变量最大的区别就是,JS 是松散型语言,决定了它只是在某一个特定时间保存某一特定的值的一个名字而已.由于在定义变量的时候不需要显示规定必须保存某种类型的值,故变量的值以及保存的 ...
- 【bzoj1005】[HNOI2008]明明的烦恼
1005: [HNOI2008]明明的烦恼 Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 4175 Solved: 1660[Submit][Stat ...
- Codeforces Round #246 (Div. 2)——D题
KMP算法,没写出来,完全不理解NEXT数组.现在理解了很多 答案都在程序中 ,不过这个思想真的很神奇, 还有毛语不好,一直没看懂题目,现在懂了, 大概是:S中前缀等于后缀,求其长度,和其在S中出现了 ...
- python开发中常用的框架
以下是15个最受欢迎的Python开源框架.这些框架包括事件I/O,OLAP,Web开发,高性能网络通信,测试,爬虫等. Django: Python Web应用开发框架 Django 应该是最出名的 ...
- D3D11 Debug Layer的bug
在开发D3D应用程序时,我们会使用Debug Layer来调试应用程序,以确保我们的程序在最终发布时没有warnings和errors.不过最近在开发应用程序时遇到了这样的问题,就是我把多个网格模型的 ...
- uva12534 Binary Matrix 2(最小费用最大流)
http://blog.csdn.net/qq564690377/article/details/17082055 做的时候觉得明显是费用流,但是真的不知道怎么建图,看了上面的博客会稍微清晰一点.后面 ...
- HDU 1548 A strange lift (Dijkstra)
A strange lift http://acm.hdu.edu.cn/showproblem.php?pid=1548 Problem Description There is a strange ...
- bat批处理延迟运行脚本(zz)
@echo off:aaapause 这里是你需要运行的程序for /l %%i in (0,1,10000) do echo %%i>nulgoto aaa 当然bat延迟运行还有其他的一些方 ...
- 2014多校第六场 1010 || HDU 4930 Fighting the Landlords (模拟)
题目链接 题意 : 玩斗地主,出一把,只要你这一把对方要不了或者你出这一把之后手里没牌了就算你赢. 思路 : 一开始看了第一段以为要出很多次,实际上只问了第一次你能不能赢或者能不能把牌出尽. #inc ...
- SQL 递归查询
WITH B (FATHER,SON,ID,ALLINFO) AS (SELECT RTRIM(LTRIM(CHAR(A.ID)))|| CHAR(ROW_NUMBER() OVER(PARTITIO ...