线程
2016-05-11 09:05
211 查看
线程创建
1.继承
public class ThreadDemo1 extends Thread{ThreadDemo1(){}
ThreadDemo1(String szName){
super(szName);
}
public void run(){
for(int count = 1,row = 1;row<10;count++,row++){
for(int i = 0;i<count;i++)
System.out.print('*');
System.out.println();
}
}
}
2.实现Runnable接口
public class ThreadDemo3 implements Runnable{@Override
public void run() {
// TODO Auto-generated method stub
for(int count = 1,row = 1;row<10;row++,count++){
for(int i = 0;i<count;i++){
System.out.print('*');
}
System.out.println();
}
}
}
线程周期
可从任意状态通过调用stop()到退出状态,一旦退出便不可逆。run()方法执行结束后,也会进入到退出状态。
当线程位于可执行状态时,在一个特定的时间点上,每一个系统处理器只会运行一个线程。此时如果线程被挂起,执行就会被中断或者进入到休眠状态,那末线程将进入不可执行状态。
线程状态的转换
1.可执行状态
stop() suspend() resume()不建议使用,可能会在虚拟机中引起死锁现象。后两个代替方法是wait()和sleep(),并且一般采取自然终止的方法,建议不要人工调用stop(0方法。wait()和notify(),notify()唤醒一个线程并允许他获得锁,notifyAll()唤醒所有等待这个对象的线程,并允许他们获得锁。
sleep()是睡眠毫秒级之后自动进入可执行状态。
线程对 I/O 操作的完成。
isAlive() true 线程在可执行或者不可执行状态,false 线程在创建或退出状态。
2.等待线程结束
public void Method1(){WaitThreadStop th1 = new WaitThreadStop();
WaitThreadStop th2 = new WaitThreadStop();
th1.start();
while(th1.isAlive()){
try{
Thread.sleep(100);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
th2.start();
}
public void Method2(){
WaitThreadStop th1 = new WaitThreadStop();
WaitThreadStop th2 = new WaitThreadStop();
th1.start();
try{
th1.join();
}
catch(InterruptedException e){
e.printStackTrace();
}
th2.start();
}
3 线程优先级
setPriority() getPriority()
线程同步
多线程可以共享资源,例如文件、数据库、内存等。当线程以并发模式访问共享数据时,共享数据可能会发生冲突。JAVA引入线程同步的概念,以实现共享资源的一致性。通过加锁来实现线程同步。获得锁的线程通过使用wait()来放弃锁。
同步变量的作用域不同,控制情况也会不同
public class ShareData {
public static String szData = "";
}
class ThreadDemo extends Thread{
private ShareData oShare;
ThreadDemo(){}
ThreadDemo(String szName,ShareData oShare){
super(szName);
this.oShare = oShare;
}
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (oShare) {
for(int i = 0;i<5;i++){
if(this.getName().equals("Thread1")){
oShare.szData = "这是第一个线程";
try{
Thread.sleep((int)Math.random()*100);
}
catch(InterruptedException e){
}
System.out.println(this.getName()+":"+oShare.szData);
}
else if(this.getName().equals("Thread2")){
oShare.szData = "这是第二个线程";
try{
Thread.sleep((int)Math.random()*100);
}
catch(InterruptedException e){
}
System.out.println(this.getName()+":"+oShare.szData);
}
}
}
}
}
线程通信
通过wait() notify() notifyAll()实现相关文章推荐
- VGA练习之图像的动态显示(后续)
- Rotate Image
- 数组、字典(16.5.11)
- 韩妆爱茉莉 创新+本土长出了张“中国脸”?
- 过滤器
- iptables 防火墙 只允许某IP访问某端口、访问特定网站
- 什么是Jdbc,怎么操作?
- java中FileInputStream,FileReader等的区别
- 你见过哪些令你瞠目结舌的 Android 代码技巧?
- 【SSH网上商城项目实战10】商品类基本模块的搭建
- CSDN-markdown编辑器使用说明
- windows下如何安装及使用github
- 大型网站技术架构 读书笔记1 大型网站架构模式
- js实现a标签超链接提交form表单的方法
- iptables禁止端口和开放端口
- 正则表达式,表单验证和事件
- 大型网站技术架构 读书笔记1 大型网站架构模式
- 顺序队列(非循环)
- 把iOS项目打包为ipa包
- 串口通信UART--读书笔记