您的位置:首页 > 编程语言 > Java开发

java-线程管理基础

2016-12-07 16:45 429 查看
线程管理

   @线程,进程,程序

 程序是计算机指令的集合,以文件形式存储在磁盘上,进程就是一个执行中的程序,进程有独立的内存空间和系统资源,一个进程由多个线程组成,多个线程共享同一个存储空间;

 


  @什么时候用线程?

当遇到一个对象要多出多个动作,并且多个动作又是穿插在一起的时候,就要使用线程的概念编写程序。

  @线程的状态迁移图

 

 

  @线程的应用

 (1)创建进程

  创建进程的方法有两种: 

   1.Runable接口创建

//创建循环语句输出数字的类
class computeOne implements Runnable{
int i=0 ; //创建了实现线程的类compute
public void run(){
for(int i=0;i<5;i++){
System.out.println(i);
}
}
}

class computeTwo implements Runnable{
public void run(){
for(int i=0;i<5;i++){
System.out.println("这个数字是"+i);
}
}
}
public class TestRun{
public static void main(String[] args){
computeOne co=new computeOne();
computeTwo ct=new computeTwo();
//创建线程对象to,tt;
Thread to=new Thread(co);
Thread tt=new Thread(ct);
to.start();  //启动线程对象to
tt.start();  //启动线程对象tt,处于就绪状态

}
}


2.thread类继承

//创建通过循环语句输出数字的类
class computeOne extends Thread{
public void run(){
for(int i=0; i<5;i++){
System.out.println(i);
}
}
}

class computeTwo extends Thread{
public void run(){
for(int i=0;i<5;i++){
System.out.println("这个数字是:"+i);
}
}
}

public class TestThread{
public static void main(String[] args){
computeOne co=new computeOne();
computeTwo ct=new computeTwo();
//启动对象ct,co
co.start();
ct.start();
}
}


 

 上面的线程是建立了,但是多次执行,结果却是没有办法预料的,不可控制的

 


 所以要想要控制线程的执行顺序,必须在执行的线程之上添加一些限制:

 ————-————–——————–——————–*

 ①设置优先权

 

   thread类中有“setPriority()”的方法,来设置其的优先权,具体的方法:

 public final void setPriority(int newPriority),其中new Priority是一个1-10的正整数,数值越大,优先级越高。所以将想要优先执行的进程设置权限高的权限即可。

 

public class TestRunTh{

public static void main(String[] args){
computeOne co=new computeOne();
computeTwo ct=new computeTwo();
//创建线程对象to,tt;
Thread to=new Thread(co);
Thread tt=new Thread(ct);
//设置线程对象的优先级
to.setPriority(10);
tt.setPriority(1);
to.start();  //启动线程对象to
tt.start();  //启动线程对象tt,处于就绪状态
}
}
//创建通过循环语句输出数字的类
class computeOne extends Thread{
public void run(){
for(int i=0; i<5;i++){
System.out.println(i);
}
}
}

class computeTwo extends Thread{
public void run(){
for(int i=0;i<5;i++){
System.out.println("这个数字是:"+i);
}
}
}


②线程让出

  线程让步:就是使当前正在运行的线程对象退出运行状态,让其它的线程运行,通过yield()的方法实现,这个方法不能将运行权让给指定的线程,只是允许这个线程让出来。

public class TestRunTh{

public static void main(String[] args){
computeOne co=new computeOne();
computeTwo ct=new computeTwo();
//创建线程对象to,tt;
Thread to=new Thread(co);
Thread tt=new Thread(ct);

to.start();  //启动线程对象to
tt.start();  //启动线程对象tt,处于就绪状态

}
}
//创建通过循环语句输出数字的类
class computeOne extends Thread{
public void run(){
for(int i=0; i<10;i++){
System.out.println(i);
//让线程暂停。
yield();
}
}
}

class computeTwo extends Thread{
public void run(){
for(int i=0;i<10;i++){
System.out.println("这个数字是:"+i);
}
}
}


  线程比进程的通信要简单容易,他们共同处于同一个内存空间,共享变量。线程的基础基本了解,下一篇我们讲线程的同步问题!请继续关注!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: