学习的第28天。
总结:
多线程:
常见方法:
public static void sleep(毫秒); public statci void yield(); public final void join();
同步代码块:
synchronized(临界资源对象){ //(原子操作) }
习题:
C12.1: 填空:
一个单CPU的机器,如何同时执行多个线程?
多个线程抢占1个CPU资源。 宏观并行,微观串行
C12.2: 选择:
public class Example implements Runnable{
public void run(){
while(true){
}
}
public static void main(String args[]){
Example ex1 = new Example();
Example ex2 = new Example();
Example ex3 = new Example();
ex1.run();
ex2.run();
ex3.run();
}
}
C. 编译成功,存在1个可运行的线程。
C12.3: 选择:
class Example implements Runnable{
public static void main(String[] args){
Thread t = new Thread(new Example());
t.start();
}
public void run(int limit){
for(int x = 0; x<limit ; x++){
System.out.println(x);
}
}
}
C. 代码编译失败,因为没有正确实现 Runnable 接口。//Runnable接口中的run方法没有参数。
C12.4: 有如下代码:
class Example{
public static void main(String[] args){
Thread.sleep(3000);
System.out.println("sleep");
}
}
A. 编译出错
C12.5: 创建两个线程:
一个线程输出100个1~26,另一个线程输出100个A~Z;一个线程使用继承,另一个用接口
class Test5 {
public static void main(String[] args) {
Thread t1 = new PrintNumber();
Thread t2 = new Thread(new PrintLetter());
t1.start();
t2.start();
}
}
class PrintNumber extends Thread{
public void run(){
Character c = 49;
for (int i = 0; i < 100; i++) {
if(c >= 49 && c <= 57){
System.out.print(c);
c ++;
}else{
c = 49;
}
}
}
}
class PrintLetter implements Runnable{
@Override
public void run() {
Character c = 65;
for (int i = 0; i < 100; i++) {
if(c >= 65 && c <= 90){
System.out.println(c);
c ++;
}else{
c = 65;
}
}
}
}
C12.6: 有如下代码:
class MyThread1 extends Thread{
Object lock;
public MyThread1(Object lock){
this.lock = lock;
}
public void run(){
synchronized(lock){ //1
for (int i = 0; i <= 10; i++) {
try {
Thread.sleep((int)Math.random()*1000);
} catch (Exception e) {
}
System.out.println("$$$");
}
}
}
}
class MyThread2 extends Thread{
Object lock;
public MyThread2(Object lock){
this.lock = lock;
}
public void run(){
synchronized(lock){ //2
for (int i = 0; i <= 10; i++) {
try {
Thread.sleep((int)Math.random()*1000);
} catch (Exception e) {
}
System.out.println("###");
}
}
}
}
public class TestMyThread{
public static void main(String[] args){
Object lock = new Object();
Thread t1 =new MyThread1(lock);
Thread t2 =new MyThread2(lock);
t1.start();
t2.start();
}
}
在1和2加上的synchronized,使线程同步的作用,如果不加则输出顺序不同。
C12.7: 有如下代码:
class MyThread extends Thread{
private String data;
//
public void run(){
synchronized(data){
for(int i = 0;i<10;i++){
try{
Tread.sleep((int)(Math.random()*1000));
}catch(Exception e){
}
System.out.println(data);
}
}
}
}
public class TestMyThread{
public static void main(String[] args){
Thread t1 = new MyThread("hello");
Thread t2 = new MyThread("world");
t1.start();
t2.start();
}
}
上述代码输出的结果是:C,交替输出