其实在网上有很多的答案,这里做一下记录
分析,两条线程,一个值,
线程在这里我分为两个类,一个常量
public class MyThread {
public int J=100;
}
public class MyThread01 extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"-"+MyThread.J++);
}
}
}
public class MyThread02 extends Thread{
public void run(){
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"-"+MyThread.J--);
}
}
}
接下来,做一个测试类,测试一下即可
我将两条线程的级别都设成最高级别,其实设置相同即可,这里两条线程就会同时抢资源
public class TestThread {
public static void main(String[] args) {
MyThread01 myThread01 = new MyThread01();
myThread01.setName("My Thread1");
myThread01.setPriority(10);
myThread01.start();
MyThread02 myThread02 = new MyThread02();
myThread02.setName("My Thread2");
myThread02.setPriority(10);
myThread02.start();
}
}