1、Runnable类使用
方法1
class Bank{
private int sum;
public void add(int n) {
sum += n;
System.out.println("sum = " + sum);
}
}
class Cus1 implements Runnable{
private Bank b = new Bank();
public void run(){
// 无锁状态会读脏数据
for( int x = 0; x < 5; x++ ){
b.add(1000);
}
}
}
class Cus2 implements Runnable{
private Bank b = new Bank();
public void run(){
synchronized(b){ // 加锁
for( int x = 0; x < 5; x++ ){
b.add(100);
}
}
}
}
public class Main{
public static void main(String []args){
//Cus1 c = new Cus1();
Cus2 c = new Cus2();
// 两个线程执行c对象
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start(); t2.start();
}
}
无锁状态下结果不稳定:
方法2
class Bank{
private int sum;
public synchronized void add(int n){
sum += n;
System.out.println("sum="+sum);
}
}
class Cus implements Runnable{
private Bank b=new Bank();
public void run(){
for(int x=0;x<5;x++) {
b.add(100);
}
}
}
public class Main{
public static void main(String []args){
Cus c=new Cus();
Thread t1=new Thread(c);
Thread t2=new Thread(c);
t1.start();
t2.start();
}
}
加锁状态下顺序正确:
2、Thread与Runnable区别
1、该段代码结果为三个线程各卖5张票,没有共享5张票
class MyThread extends Thread {
private int ticket=5;
public void run() {
for(int i=0;i<20;i++) {
if(this.ticket>0) {
System.out.println("卖票:ticket"+this.ticket--);
}
}
}
}
public class Main {
public static void main(String[] args) {
MyThread mt1=new MyThread();
MyThread mt2=new MyThread();
MyThread mt3=new MyThread();
mt1.start();
mt2.start();
mt3.start();
}
}
2、三个线程共享5张票。
class MyThread implements Runnable {
private int ticket=5;
public void run() {
for(int i=0;i<20;i++) {
if(this.ticket>0) {
System.out.println("卖票:ticket"+this.ticket--);
}
}
}
}
public class Main {
public static void main(String[] args) {
MyThread mt=new MyThread();
new Thread(mt).start();
new Thread(mt).start();
new Thread(mt).start();
}
}