Java thread(3)

mac2022-06-30  21

    线程间的调度策略

    通常是选择优先级高的线程,但是若发生以下情况则终止线程的运行:    1 调用yield 让出对cpu的占用权。

    2 调用sleep

    3 线程由于I/O操作而受阻

    4 更高优先级的线程出现

    5 时间片用完

    线程类的一些相关方法

    isAlive()判断线程的死活、getPriority()得到线程的优先级、setPriority()设置线程的优先级、leep()方法使得线程休眠、yield方法放弃线程对cpu的使用权。

    对于两个线程何时公用一个变量 何时私自拥有自己的变量的比较

    当变量是类的成员变量的时候,这个变量被两个线程共享,如果是局部变量,比如定义在run方法中,这两个线程各自有自己的变量。

 

//情况一: //两个线程 各自都有私有的变量 因为int变量声明在run方法中 结果会出来20个数 package com.javase.thread; public class threadTest2 { public static void main(String[]args){ Runnable r=new helloThread(); Thread t1=new Thread(r); Thread t2=new Thread(r); t1.start(); t2.start(); } } class helloThread implements Runnable{ public void run() { int i=0; while(true){ i++; try { Thread.sleep((long)Math.random()*2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(i>10) {break;} System.out.println("the number is "+i); } } } //情况二: //int变量声明在类中 是类的成员变量 两个线程会共享着同一个公有的变量 结果会打印出来10个数字 package com.javase.thread; public class threadTest2 { public static void main(String[]args){ Runnable r=new helloThread(); Thread t1=new Thread(r); Thread t2=new Thread(r); t1.start(); t2.start(); } } class helloThread implements Runnable{ int i=0; public void run() { while(true){ i++; try { Thread.sleep((long)Math.random()*2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(i>10) {break;} System.out.println("the number is "+i); } } } //情况三: //在第一种共享成员变量的情况下 如果生成两个runnable接口(helloThread对象) //则每个线程各自仍然会有自己的变量 不会发生冲突 两个helloThread对象 有各自的变量 结果会出来20个数字 package com.javase.thread; public class threadTest2 { public static void main(String[]args){ Runnable r1=new helloThread(); Runnable r2=new helloThread(); Thread t1=new Thread(r1); Thread t2=new Thread(r2); t1.start(); t2.start(); } } class helloThread implements Runnable{ int i=0; public void run() { while(true){ i++; try { Thread.sleep((long)Math.random()*2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(i>10) {break;} System.out.println("the number is "+i); } } }

转载于:https://www.cnblogs.com/Goden/p/3836664.html

最新回复(0)