学习记录分享(多线程)

1.一个单CPU的机器,如何同时执行多个线程?请简述其原理
单CPU在任何时间点上,只能运行一个线程,实现同时执行多个线程是通过串行,在不同的线程之间通过CPU时间片控制切换执行不同的线程。
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 ,只有主方法一个线程,没有创建新的线程类

3.(线程的创建)有以下代码
在这里插入图片描述
在这里插入图片描述

public class TestExample implements Runnable {
	public static void main(String[] args) {
		Thread t = new Thread(new TestExample());
		t.start();
	}

	public void run(int limit) {//Runnable接口中的run方法是无参的,覆盖也必须与原有的保持一致
		for (int x = 0; x < limit; x++) {
			System.out.println(x);
		}
	}

}

C 没有正确覆盖run方法,所以相当于没有覆盖,没有实现Runnable接口

4.(sleep方法)有如下代码
在这里插入图片描述

class Example{
	public static void main(String[] args) {
		Thread.sleep(3000);//受查异常,必须处理
		System.out.println("sleep");
	}
}

A

5.(线程的创建)创建两个线程,要求如下:
Ⅰ.一个线程输出100个1~26,另一个线程输出100个A ~Z
Ⅱ.一个线程使用继承Thread类的写法,另一个线程使用实现Runnable接口的写法。

public class Test05 {

	public static void main(String[] args) {
		Thread1 t1 = new Thread1();
		t1.start();
		Runnable1 ru = new Runnable1();
		Thread t2 = new Thread(ru);
		t2.start();

	}

}
class Thread1 extends Thread{
	public void run() {
		for(int i=1;i<=100;i++) {
			System.out.println("1~26");
		}
	}
}
class Runnable1 implements Runnable{
	public void run() {
		for(int i=1;i<=100;i++) {
			System.out.println("A~Z");
		}
	}
}

部分运行结果:
在这里插入图片描述

6.(线程的同步)有如下代码

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();

	}

}
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("###");
			}
		}
	}
}

在//1和//2处加上的synchronized的作用是对临界资源对象加锁,保证原子操作只能由首先拿到锁的的线程进行操作。
如果不加,原子操作会在两个线程之间交替执行

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值