- 实例化两个线程,同时对⼀个数字进⾏操作。⼀个线程对这个数字进⾏加1,另外⼀个线程对这个数字进⾏减⼀。输出每⼀次的操作之后的这个数字的值。
public class Work1 {
private static int number = 10;
public static void main(String[] args) {
Runnable runnable1 = () -> {
while (true) {
System.out.println(Thread.currentThread().getName() + "对数字加1,结果是:" + ++number);
}
};
Runnable runnable2 = () -> {
while (true) {
System.out.println(Thread.currentThread().getName() + "对数字减1,结果是:" + --number);
}
};
Thread thread1 = new Thread(runnable1,"加线程");
Thread thread2 = new Thread(runnable2,"减线程");
thread1.start();
thread2.start();
}
}
- 有五个⼈同时过⼀个独⽊桥,⼀个独⽊桥同时只能允许⼀个⼈通过。每⼀个⼈通过独⽊桥的时间是随机在 [5,10] 秒,输出这个独⽊桥上每⼀个⼈的通过详情,例如:张三开始过独⽊桥了… 张三通过独⽊桥了!
public class Work2 {
public static void main(String[] args) {
Bridge bridge = new Bridge();
Thread t1 = new Thread(bridge,"张三");
Thread t2 = new Thread(bridge,"李四");
Thread t3 = new Thread(bridge,"王五");
Thread t4 = new Thread(bridge,"赵六");
Thread t5 = new Thread(bridge,"田七");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
class Bridge implements Runnable{
int time = (int)(Math.random()*5+5);
@Override
public void run() {
synchronized (this){
System.out.println(Thread.currentThread().getName()+"开始过独木桥");
try{
Thread.sleep(time*100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"通过了独木桥");
}
}
}
- 写出以下程序可能得执⾏结果
class MyThread extends Thread {
public void run() {
try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
}
System.out.println("MyThread running");
}
}
public class ThreadTest {
public static void main(String argv[]) {
MyThread t = new MyThread();
t.run();
t.start();
System.out.println("Thread Test");
}
}
输出结果:
MyThread running
Thread Test
MyThread running过程:
- MyThread t = new MyThread();
- t.run(); 进⼊run的内部,先让主线程睡3000毫秒,由于当其的⼦线程还没有,所以,程序等待,什么都不做
- 睡醒了,执⾏ System.out.println(“MyThread running”);
- t.start();在这⾥有了三个线程垃圾回收,主线程,t⼦线程,所以下⾯的处理要分情况
- 继续执⾏主线程System.out.println(“Thread Test”); 然后主线程释放cpu,t线程抢到cpu后,开始运⾏,执⾏run⽅法 ,所以t线程先执⾏Thread.currentThread().sleep(3000); 睡3000毫秒继续执⾏System.out.println(“My Thread running”);
- t线程抢到cpu,执⾏run⽅法 执⾏Thread.currentThread().sleep(3000);,分线程睡 30000毫秒 主线程抢到cpu,继续执⾏System.out.println(“Thread Test”); 主线程执⾏完后,释放cpu ,t线程睡醒后重新抢到cpu ,执⾏System.out.println(“My Thread running”)
- 需求说明
⼀个线程打印0-9的随机数字,⼀个线程打印随机的26个⼩写字⺟。
⽅式⼀:通过Thread的两个不同⼦类的线程对象实现.
import java.util.*;
class Number extends Thread{
Random random = new Random();
public void run(){
System