java基础温习 -- Thread
启动线程两种方式:
1. 实现Runnable接口;
2. 继承Thread类。
选用:能使用接口,就不用从Thread类继承。
使用继承的方法不够灵活,从这个类继承了就不能从其他类继承;
实现接口后,还可以从其他类继承,也可以再实现其他接口。

线程状态转换:

常用方法:
join()
Waits for this thread to die.合并到当前线程执行,类似于方法调用了。
yield()
A hint to the scheduler that the current thread is willing to yield its current use of a processor. 让出CPU,给其他线程执行机会。
setPriority(int newPriority)
Changes the priority of this thread.
关闭线程
stop()
Deprecated.
This method is inherently unsafe.
Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack).
If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior.
Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running.
The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running.
If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait.
For more information, see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.
举例:
public class TestThread4 {
public static void main(String args[]){
Runner4 r = new Runner4();
Thread t = new Thread(r);
t.start();
for(int i=0;i<100000;i++){
if(i%10000==0 & i>0)
System.out.println("in thread main i=" + i);
}
System.out.println("Thread main is over");
r.shutDown();//关闭线程推荐方法。flag=false,run方法结束、线程结束。
//t.stop(); stop方法已废弃,
}
}
class Runner4 implements Runnable {
private boolean flag=true;
public void run() {
int i = 0;
while (flag==true) {
System.out.print(" " + i++);
}
}
public void shutDown() {
flag = false;
}
}
多线程同步
一般而言,需要同步的对象,在改的相关方法上加锁(两个方法都修改了同样的值,两个方法都加同步),读时不加锁(允许多个线程同时读)。
syschronized
对象的互斥锁标记,保证在任一时刻,只能有一个线程访问该对象。
关键字synchronized与互斥锁联系。
wait()
发生一个阻塞事件。
public final void wait()
throws InterruptedExceptionCauses the current thread to wait until another thread invokes the notify() method or the notifyAll() method
for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).
与sleep区别:
- wait时其他线程可以访问锁定对象;(故调用wait方法时必须锁定该对象。)
- sleep时别的线程不能访问。
notifiy()/notifyAll()
叫醒某一个/所有 wait在某个对象上的线程。
public final void notify()
Wakes up a single thread that is waiting on this object's monitor.
If any threads are waiting on this object, one of them is chosen to be awakened.
The choice is arbitrary and occurs at the discretion of the implementation.
A thread waits on an object's monitor by calling one of the wait methods.
生产者消费者模式
public class ProducerConsumer {
public static void main(String[] args) {
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);
Consumer c = new Consumer(ss);
new Thread(p).start();
new Thread(p).start();
new Thread(p).start();
new Thread(c).start();
}
}
class WoTou {
int id;
WoTou(int id) {
this.id = id;
}
public String toString() {
return "WoTou : " + id;
}
}
class SyncStack {
int index = 0;
WoTou[] arrWT = new WoTou[6];
public synchronized void push(WoTou wt) {
while(index == arrWT.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
arrWT[index] = wt;
index ++;
}
public synchronized WoTou pop() {
while(index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
index--;
return arrWT[index];
}
}
class Producer implements Runnable {
SyncStack ss = null;
Producer(SyncStack ss) {
this.ss = ss;
}
public void run() {
for(int i=0; i<20; i++) {
WoTou wt = new WoTou(i);
ss.push(wt);
System.out.println("生产了:" + wt);
try {
Thread.sleep((int)(Math.random() * 200));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
SyncStack ss = null;
Consumer(SyncStack ss) {
this.ss = ss;
}
public void run() {
for(int i=0; i<20; i++) {
WoTou wt = ss.pop();
System.out.println("消费了: " + wt);
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
java基础温习 -- Thread的更多相关文章
- java基础温习 -- Thread synchronized关键字
synchronized 基本规则 1. 当一个线程访问“某对象”的“synchronized方法”或者“synchronized代码块”时,其他线程对“该对象”的该“synchronized方法”或 ...
- java基础(26):Thread、线程创建、线程池
1. 多线程 1.1 多线程介绍 学习多线程之前,我们先要了解几个关于多线程有关的概念. 进程:进程指正在运行的程序.确切的来说,当一个程序进入内存运行,即变成一个进程,进程是处于运行过程中的程序,并 ...
- JAVA基础(多线程Thread和Runnable的使用区别(转载)
转自:http://jinguo.iteye.com/blog/286772 Runnable是Thread的接口,在大多数情况下“推荐用接口的方式”生成线程,因为接口可以实现多继承,况且Runnab ...
- 【java基础】Thread类之join方法
- java基础温习 -- 多态
1. 基本概念 多态是指一个事物有不同的表现形式或形态. 多态存在的三个必要条件:要有继承.要有重写.父类变量引用子类对象. 当使用多态方式调用方法时: 首先检查父类中是否有该方法,如 ...
- Java基础-进程与线程之Thread类详解
Java基础-进程与线程之Thread类详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.进程与线程的区别 简而言之:一个程序运行后至少有一个进程,一个进程中可以包含多个线程 ...
- [Java面经]干货整理, Java面试题(覆盖Java基础,Java高级,JavaEE,数据库,设计模式等)
如若转载请注明出处: http://www.cnblogs.com/wang-meng/p/5898837.html 谢谢.上一篇发了一个找工作的面经, 找工作不宜, 希望这一篇的内容能够帮助到大 ...
- Java基础知识【上】(转载)
http://blog.csdn.net/silentbalanceyh/article/details/4608272 (最终还是决定重新写一份Java基础相关的内容,原来因为在写这一个章节的时候没 ...
- Java基础加强之多线程篇(线程创建与终止、互斥、通信、本地变量)
线程创建与终止 线程创建 Thread类与Runnable接口的关系 public interface Runnable { public abstract void run(); } public ...
随机推荐
- vue sChart组件使用页面一片空白问题及示例
参考:https://www.ctolib.com/mip/lin-xin-vue-schart.html 在网上其他示例里,我试验后发现:渲染到<canvas id="myChart ...
- Js_案例(电灯)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- mysql的双主模式
mysql主主复制配置 server1 ip:192.168.0.231server2 ip:192.168.0.234 更改两台主机的mysql配置文件vim /etc/my.cnfserver1添 ...
- Leetcode274.H-IndexH指数
原题的中文翻译不是很好,所以给出英文版. Given an array of citations (each citation is a non-negative integer) of a rese ...
- [转]Nginx配置详解
Nginx是lgor Sysoev为俄罗斯访问量第二的rambler.ru站点设计开发的.从2004年发布至今,凭借开源的力量,已经接近成熟与完善. Nginx功能丰富,可作为HTTP服务器,也可作为 ...
- Python 读取本地*.txt文件 替换 内容 并保存
# r 以只读的方式打开文件,文件的描述符放在文件的开头# w 打开一个文件只用于写入,如果该文件已经存在会覆盖,如果不存在则创建新文件 #路径path = r"D:\pytho ...
- CSS压缩
通过W3C 统一验证工具的检测没有错误后,为了提高加载速度和节约空间(相对来说,css量很少的情况下,几乎没啥区别),可以通过css压缩工具把css进行压缩. w3c css压缩 http://too ...
- Divide by Zero 2018 and Codeforces Round #474 (Div. 1 + Div. 2, combined)G - Bandit Blues
题意:求满足条件的排列,1:从左往右会遇到a个比当前数大的数,(每次遇到更大的数会更换当前数)2.从右往左会遇到b个比当前数大的数. 题解:1-n的排列,n肯定是从左往右和从右往左的最后一个数. 考虑 ...
- hadoop Datanode多目录配置
1. DataNode也可以配置成多个目录,每个目录存储的数据不一样.即:数据不是副本2.具体配置如下 hdfs-site.xml <property> <name>dfs.d ...
- 数组那些事(slice,splice,forEach,map,filter等等)
周五,再过会要下班了,刚才把<javascript高级程序设计>数组这块又看了下,加深下记忆.今天来继续练练笔,嘿嘿!(写下自己印象不深的东西) 一.数组的定义(数组定义分为两种) 方法一 ...
