在千锋学习的第二十八天
加倍努力!
今天学习了线程,分别就线程的创建 和线程的安全
习题
1一个cpu 的机器,执行的任务每个执行一段时间。线程呈现并发执行
2
package com.lichenchen.xiti;
public class TestDemo1 {
public static void main(String[] args) {
Example ex1 =new Example();
Example ex2 =new Example();
Example ex3 =new Example();
ex1.run();
ex2.run();
ex3.run();
}
}
class Example implements Runnable{
public void run(){
while(true){}
}
}
选择正确答案
C 代码编译成功,存在一个可运行的线程
3
package com.lichenchen.xiti;
class Example1 implements Runnable{
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t = new Thread(new Example());
t.start();
}
public void run(int limit){
for(int i =0;i<limit;i++){
System.out.println(i);
}
}
}
C 代码编译失败,因为没有正确实现Runnable 接口
package com.lichenchen.xiti;
public class Example2 {
public static void main(String[] args) {
//Thread.sleep(3000);
System.out.println("sleep");
}
}
编译出错
5
package com.lichenchen.xiti;
import java.util.Random;
public class TestDemo4 {
public static void main(String[] args) {
MyThread t =new MyThread();
t.start();
MyThread2 t1 =new MyThread2();
Thread th =new Thread(t1);
th.start();
}
}
class MyThread extends Thread{
public void run(){
Random r =new Random();
for(int i =1;i<=100;i++){
System.out.println(r.nextInt(26)+"\t -/"+i);
}
}
}
class MyThread2 implements Runnable{
@Override
public void run() {
for(int c =1;c<=100;c++){
Random r1 =new Random();
int ran =r1.nextInt(26);
Character ac =(char)(ran+65);
System.out.println(ac+"\t"+c);
}
}
}
6
package com.lichenchen.xiti;
public class TestMyThread {
public static void main(String[] args) {
Object lock =new Object();
Thread t1 =new MyThread3(lock);
Thread t2 =new MyThread4(lock);
t1.start();
t2.start();
}
}
class MyThread3 extends Thread{
Object lock;
public MyThread3(Object lock) {
super();
this.lock = lock;
}
public void run(){
//synchronized(lock){
for(int i =0;i<=10;i++){
try{
Thread.sleep((int)(Math.random()*1000));
System.out.println("程序技术");
}catch (Exception e){
System.out.println("$$$");
}
//}
}
}
}
class MyThread4 extends Thread{
Object lock;
public MyThread4(Object lock) {
super();
this.lock = lock;
}
public void run(){
//synchronized (lock) {//2
for(int i=0;i<=10;i++){
try{
Thread.sleep((int)(Math.random()*1000));
System.out.println("我也休眠啦");
}catch(Exception e){
}
System.out.println("####");
//}
}
}
}
在加入synchronized 同步 只能以一个线程访问内部代码
如果不加 线程会交替执行
package com.lichenchen.xiti;
public class TestMyThreads {
public static void main(String[] args) {
Thread t1 =new MyThreadsd("hello");
Thread t2 =new MyThreadsd("world");
t1.start();
t2.start();
}
}
class MyThreadsd extends Thread{
private String data;
public MyThreadsd(String data) {
super();
this.data = data;
}
public void run(){
synchronized (data) {
for(int i =0;i<10;i++){
try{
Thread.sleep((int)(Math.random()*1000));
}catch(Exception e){
}
System.out.println(data);
}
}
}
}
C 线程不同步 所以交替输出hello 和word