学习的第29天。
总结:
多线程:
增、删、改的操作要加锁,读不加
线程的组成:
CPU时间片、运行数据(堆空间、栈空间)
获取线程池:
ExecutorService:线程池接口,可通过submit(Runnable task)提交任务代码。
Executors.new Fixed/Cached ThreadPool(int n);//获取固定数量的线程池
Callable接口:
JDK5加入,具有泛型返回值,可以声明异常
习题:
C12.8: 希望能够一次输出100个aaa或bbb。
class MyThread extends Thread{
private String data;
public MyThread(String data){
this.data = data;
}
public void run(){
for(int i=0;i<100;i++){
System.out.println(data);
}
}
}
public class TestMyThread{
public static void main(String[] args){
Thread t1 = new MyThread("aaa");
Thread t2 = new MyThread("bbb");
t1.start();
t2.start();
}
}
C,把run方法中的内容都放在synchronized(System.out)代码块中
C12.9: 改错:
class MyThread1 implements Runnable{
public void run(){
for(int i=0;i<100;i++){
this.sleep((int)Math.random()*1000);//-------------------
Systme.out.println("hello");
}
}
}
class MyThread2 extends Thread{
public void run() throws Exception{//--------------------
for(int i =0;i<100;i++){
this.sleep((int)Math.random()*1000);
Systme.out.println("world");
}
}
}
public class TestMyThread{
public static void main(String[] args){
Runnable t1 = new MyThread1();//------------------
Thread t2 = new MyThread2();
t1.start();
t2.start();
}
}
class MyThread1 implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep((int) Math.random() * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("hello");
}
}
}
class MyThread2 extends Thread {
public void run() {
for (int i = 0; i < 100; i++) {
try {
this.sleep((int) Math.random() * 1000);//应该以静态方法访问 Math
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("world");
}
}
}
public class TestMyThread {
public static void main(String[] args) {
Thread t1 = new Thread(new MyThread1());
Thread t2 = new MyThread2();
t1.start();
t2.start();
}
}