1.Runnable 和 Thread区别
Runnable的实现方式是实现其接口即可
第一步:实现Runnable接口,重写run方法
public class MyRunnable implements Runnable{ @Override public void run(){ } }
第二步使用MyRunnable:
new Thread(new MyRunnable).start();
Thread的实现方式是继承其类
public class MyThread extends Thread{ @Override public void run(){
} }
class TestMyThread{
MyThread mythread = new MyThread();
mythread.start();
}
多线程原理(
转载
作者:itbird01
链接:https://www.jianshu.com/p/333ce4b3d5b8
来源:简书):
相当于玩游戏机,只有一个游戏机(cpu),可是有很多人要玩,于是,start是排队!等CPU选中你就是轮到你,你就run(),当CPU的运行的时间片执行完,这个线程就继续排队,等待下一次的run()。
调用start()后,线程会被放到等待队列,等待CPU调度,并不一定要马上开始执行,只是将这个线程置于可动行状态。然后通过JVM,线程Thread会调用run()方法,执行本线程的线程体。
strart()是启动线程的方法,run()是线程体(内容顺序执行),无论是Runnable还是Thread,都是先启动线程等待Cpu调度,执行线程体。
public class Test2 { public static void main(String[] args) { MyThread t1 = new MyThread(); new Thread(t1, "线程1").start(); new Thread(t1, "线程2").start(); } public static class MyThread extends Thread { private int total = 10; @Override public void run() { for (int i = 0; i < 10; i++) { synchronized (this) { if (total > 0) { try { Thread.sleep(100); System.out.println(Thread.currentThread().getName() + "卖票---->" + (this.total--)); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
public class Test3 { public static void main(String[] args) { MyRunable t1 = new MyRunable(); new Thread(t1, "线程1").start(); new Thread(t1, "线程2").start();
//当以Thread方式去实现资源共享时,实际上源码内部是将thread向下转型为了Runnable,实际上内部依然是以Runnable形式去实现的资源共享 } public static class MyRunable implements Runnable { private int total = 10; @Override public void run() { for (int i = 0; i < 10; i++) { synchronized (this) { if (total > 0) { try { Thread.sleep(100); System.out.println(Thread.currentThread().getName() + "卖票---->" + (this.total--)); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } }
原文:https://www.cnblogs.com/liyanglin/p/13019363.html