简单的线程控制
package Thread;
public class Demo01 {
public static void main(String[] args) {
Thread t0 = new Thread(new NormalRunner());
Thread t1 = new Thread(new YieldRunner());
Thread t2 = new Thread(new SleepRunner());
Thread t3 = new Thread(new NormalRunner());
t0.setName("normal");
t1.setName("yield");
t2.setName("sleep");
t3.setName("join");
t3.setPriority(1);//设置优先级1-10,10最高
t2.start();
t1.start();
t0.start();
t3.start();
for (int i = 0; i < 50; i++) {
System.out.println(Thread.currentThread().getName()+i);//直接通过类引用方法
if(i==30){//当i==30时t3线程加入
try {
t3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class NormalRunner implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
}
class SleepRunner implements Runnable{//线程的睡眠控制
@Override
public void run() {
try {
Thread.sleep(1);//线程睡眠100毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
}
class YieldRunner implements Runnable{//线程让步
@Override
public void run() {
for (int j = 0; j < 10; j++) {
System.out.println(Thread.currentThread().getName()+j);
if(j==5){
Thread.yield();//让步
}
}
}
}
简单的分析
package Thread;
public class Demo02 {
public static void main(String[] args) {
MyRunner mr = new MyRunner();
Thread t1 = new Thread(mr);
t1.start();//语句顺序会影响结果
mr.method2();
}
}
class MyRunner implements Runnable{
private int b =0;
@Override
public void run() {
method1();
}
public synchronized void method1(){
b = 100;//先赋值再睡
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("b="+b);
}
public void method2(){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
b=500;//先睡再赋值,所以最后b=500
}
}
返回结果:b=500