第1关:创建多线程
代码:
package step1;
class CreateThreadPractice {
public static void main(String[] args) {
MyThread myThread = new MyThread();
// ---------------------Begin------------------------
//开启线程
myThread.start();
// ---------------------End------------------------
}
}
// ---------------------Begin------------------------
//继承Thread编写名为MyThead的类,代码内容为循环输出10遍: 线程在运行......
class MyThread extends Thread {
@Override
public void run() {
for(int i = 1; i <= 10; ++ i )
System.out.println("线程在运行......");
}
}
// ---------------------End------------------------
第2关:使用Callable接口创建多线程
代码:
package step2;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
class MyThread_callable implements Callable<String> {
private final String threadName;
public MyThread_callable(String threadName) {
this.threadName = threadName;
}
@Override
public String call() throws Exception {
for (int i = 0; i < 5; i++) {
System.out.println(threadName + "的call()方法在运行");
}
return threadName + "返回结果:" + threadName;
}
}
public class CallableExample {
public static void main(String[] args) throws InterruptedException, ExecutionException {
MyThread_callable myThread1 = new MyThread_callable("thread1");
MyThread_callable myThread2 = new MyThread_callable("thread2");
FutureTask<String> ft1 = new FutureTask<>(myThread1);
FutureTask<String> ft2 = new FutureTask<>(myThread2);
Thread thread1 = new Thread(ft1);
Thread thread2 = new Thread(ft2);
thread1.start();
thread2.start();
String result1 = ft1.get();
String result2 = ft2.get();
System.out.println(result1);
System.out.print(result2);
}
}
第3关:使用Runable接口创建多线程
代码:
package step3;
// ---------------------Begin------------------------
//定义一个实现Runnable接口的实现类,类名必须命名为MyThread_runable
//tips: 输出语句为:Thread.currentThread().getName()+"的run()方法在运行"
class MyThread_runable implements Runnable {
@Override
public void run() {
for(int i = 0; i < 3; ++ i )
System.out.println(Thread.currentThread().getName()+"的run()方法在运行");
}
}
// ---------------------End------------------------
第4关:多线程中的售票问题
代码:
package step4;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SellTicket extends Thread {
//多线程共享资源,票数为30张
private static ReentrantLock lock = new ReentrantLock();
private static int ticket = 30;
@Override
public void run() {
while (true) {
try {
lock.lock();
if (ticket > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
System.out.println("卖出了第" + ticket + "张票");
ticket--;
} else {
System.out.println("票卖完了");
System.exit(0);
}
} finally {
lock.unlock();
}
}
// ---------------------End------------------------
}
}
/********* End *********/
第5关:知识回顾
选择题答案是:
A D B