@感谢小毛豆
今天一个同学说在面试的时候,遇到了一个面试题,两个线程交替打印1到10,感觉还是很有意思的就发表一下
实现Runnable()接口
要实现交替打印意味着者两个线程要交替执行某一段相同代码,以相同的逻辑方式等待和唤醒其他的线程,首先写执行的逻辑代码
package method1;
/**
* Create by Kenson on 2019/4/3
*/
public class MyTask {
public synchronized void PrintNum(int i){
this.notify();
System.out.println(Thread.currentThread().getName()+":"+i);
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
使用匿名内部类的方法创建线程:因为在同一对象中,所以他们的琐是相同的.
package method1;
/**
* Create by Kenson on 2019/4/3
*/
public class SwapPrint {
static int r =0;
public static void main(String[] args) {
MyTask task = new MyTask();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
r++;
task.PrintNum(r);
if(r>=10){
System.exit(1);
}
}
}
});
thread1.setName("我是线程1");
thread1.start();
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
r++;
task.PrintNum(r);
if(r>=10){
System.exit(1);
}
}
}
});
thread2.setName("我是线程2");
thread2.start();
}
}
打印结果:
继承Thread类的实现方式:
和继承接口的方式一样,这里首先写一个公用的代码块:
package method1;
/**
* Create by Kenson on 2019/4/3
*/
public class ThreadModel extends Thread {
static int r = 1;
@Override
public void run() {
synchronized (ThreadModel.class){
for (int i = 0; i < 5; i++) {
ThreadModel.class.notify();
System.out.println(Thread.currentThread().getName()+":"+ r);
r++;
if (r>=10){
return;
}
try {
ThreadModel.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
值得注意的是这里要加上同步锁来实现需求,每个对象都有一把琐,这里使用ThreadModel.class来当作琐
实现需求代码:
package method1;
/**
* Create by Kenson on 2019/4/3
*/
public class ThreadTest {
public static void main(String[] args) throws InterruptedException {
ThreadModel testThread1 = new ThreadModel();
testThread1.setName("我是线程1");
testThread1.start();
ThreadModel testThread2 = new ThreadModel();
testThread2.setName("我是线程2");
testThread2.start();
}
}
打印结果: