前提:
1:这两种方法都是通过重写run(),在run()方法中实现运行在线程上的代码
2:Runnable相比于Thread更适合多个相同程序代码去处理同一个资源的情况,通常采用Runnable
3:被synchronized 修饰的方法在某一时刻只允许一个线程访问
继承Thread类创建多线程
package rjxy;
/*
public static void main(String[] args) {
MyThread t1=new MyThread("我是线程1");
MyThread t2=new MyThread("我是线程2");
t1.start();
t2.start();
}
}
class MyThread extends Thread{
public MyThread() {
super();
}
public MyThread(String name) {
super(name);
}
public void run(){
for (int i = 0; i <10; i++) {
System.out.println(this.getName());
}
}
}
实现Runnable接口创建多线程
package rjxy;
public class Thread2 {
/*
* 通过实现Runnable接口的方式创建一个线程,要求main线程打印100次“main”,新线程打印50次“new”
*/
public static void main(String[] args) {
MyRunnable mr=new MyRunnable();
Thread t1=new Thread(mr);
t1.start();
for (int i = 0; i < 100; i++) {
System.out.println("main");
}
}
}
class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i <50; i++) {
System.out.println("new");
}
}
}
一个栗子
package rjxy;
/*
* 模拟3个来时同时分发80份笔记,每个老师相当于一个线程。
*/
public static void main(String[] args) {
MyRunnable_paper mrp=new MyRunnable_paper();
//新建是三个线程
new Thread(mrp,"赵老师").start();
new Thread(mrp,"张老师").start();
new Thread(mrp,"李老师").start();
}
}
class MyRunnable_paper implements Runnable{
private static int num=80;
@Override
public void run() {
while(true){
papers();
}
}
public synchronized void papers(){
if (num>0) {
System.out.println(Thread.currentThread().getName()+"正在发"+num--);
}else{
System.exit(0);
}
}
}
第二个栗子
package rjxy;
public class Thread4 {
// * 编写10个线程,第一个线程从1加到10, 第2个线程从11加到20,......第10个线程从91加到100,最后把10个线程的结果相加。
public static void main(String[] args) throws InterruptedException {
Thread [] mys=new Thread[10];
//多态
for (int i = 0; i < 10; i++) {
mys[i]=new MyThread_add(i*10+1);
mys[i].start();
}
for (int i = 0; i < 10; i++) {
mys[i].join();
}
System.out.println( MyThread_add.getSum());
}}
private int startNum;
private static int sum=0;
public MyThread_add() {
super();
// TODO Auto-generated constructor stub
}
//初始化开始值
public MyThread_add(int startNum) {
this.startNum=startNum;
}
int sum=0;
for (int i = 0; i <10; i++) {
sum+=startNum+i;
}
add(sum);
}
public synchronized void add(int num){
sum+=num;
}
public static int getSum(){
return sum;
}
}
第三个栗子
//窗口售票的栗子
public class Main {
public static void main(String[] args) {
MyRunnable task =new MyRunnable();//创建线程的任务类对象
new Thread(task,"窗口 1").start();//创建线程并起名
new Thread(task,"窗口 2").start();//创建线程并起名
new Thread(task,"窗口 3").start();//创建线程并起名
new Thread(task,"窗口 4").start();//创建线程并起名
}
}
class MyRunnable implements Runnable{
static private int tickets=500;//票数
@Override
public void run() {
while(true) {//无数次调用直到system.exit(0)
sendTicket();
}
}
//定义售票的方法,该方法某一时刻允许一个线程访问
public synchronized void sendTicket() {
try {
Thread.sleep(10);//线程休眠10秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//售票
if (tickets>0) {
System.out.println(Thread.currentThread().getName()+"---卖出去的票"+tickets--);
}else {
System.exit(0);
}
}
}