您的位置:首页 > 其它

线程

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()实现
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: