线程方法
1. Thread.yield();
很多人翻译成线程让步。顾名思义,就是说当一个线程使用了这个方法之后,它就会把自己CPU执行的时间让掉,让自己或者其它的线程运行。
使当前线程从执行状态(运行状态)变为可执行态(就绪状态)。cpu会从众多的可执行态里选择,也就是说,当前也就是刚刚的那个线程还是有可能会被再次执行到的,并不是说一定会执行其他线程而该线程在下一次中不会执行到了。
2. dd.join();
(有详细代码示例)https://www.cnblogs.com/lcplcpjava/p/6896904.html
阻塞时将当前线程暂停,直至调用join函数所对应的线程执行完毕,才继续执行程序。
左边为 子线程使用 了 join,阻塞了主调线程所以等子线程执行完,主线程才能继续进行
右图为不加join时线程交替进行。
3. xc2.setPriority(Thread.NORM_PRIORITY + 3);
xc2为Thread类的对象
括号中3为给原来的级别+3,数字越大优先级越高
//线程默认级别是5,
优先级越高的线程更容易抢到下一次交替执行线程的机会
4. 线程同步方法(7种)
详细代码:http://www.cnblogs.com/XHJT/p/3897440.html
- synchronized关键字修饰的方法
- synchronized关键字修饰的语句块。
- 使用特殊域变量(volatile)实现线程同步
- 使用重入锁实现线程同步
- 使用局部变量实现线程同步
- 使用阻塞队列实现线程同步
- 使用原子变量实现线程同步
三种线程创建方法
1.Thread类实现
public class 线程create方法1 extends Thread{
public void run()
{
for(int i=0;i<50;i++)
System.out.println(this.getName()+i);
}
public static void main(String[] args) {
线程create方法1 th=new 线程create方法1();
th.start();
}
}
Runnable 接口
public class 线程create方法2 implements Runnable{
public static void main(String[] args) {
线程create方法2 c1=new 线程create方法2();
线程create方法2 c2=new 线程create方法2();
Thread th=new Thread(c1);
th.start();
Thread th2=new Thread(c2);
th2.start();
}
public void run() {
for(int i=0;i<50;i++)
System.out.println(Thread.currentThread().getName()+"ccc "+i);
}
}
Callable 接口(JDK5)
package 线程;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class 线程create方法3 implements Callable<Object>{
public static void main(String[] args) throws InterruptedException, ExecutionException {
线程create方法3 c=new 线程create方法3();
//
FutureTask<Object> ft1=new FutureTask<> (c);//与Runnable接口不一样
//需要使用FutureTask封装Callable接口
//可以用来接收返回值
Thread th=new Thread(ft1);
th.start();
/
FutureTask<Object> ft2=new FutureTask<> (c);//与Runnable接口不一样
//需要使用FutureTask封装Callable接口
//可以用来接收返回值//返回值就是call方法中的return值
Thread th2=new Thread(ft2);
th2.start();
///
System.out.println("1的返回结果:"+ft1.get());
System.out.println("2的返回结果:"+ft2.get());
}
public Object call() throws Exception {
//重写接口中的call方法
int i=0;
while(i<5)
{
System.out.println(Thread.currentThread().getName()+"的call方法运行"+i);
i++;
}
return "t";//object类型
//return i;
}
}