/** extends Thread 非实现变量共享 */
public class MyThread extends Thread {
private int count = 3;
public MyThread(String threadName) {
super();
this.setName(threadName);
}
@Override
public void run() {
while (count > 0) {
count--;
System.out.println("thread " + Thread.currentThread().getName()
+ " count = " + count);
}
}
/**
* 使用extends Thread 创建3个线程(即创建3个MyThread实例对象)
* 每个线程都有各自的count变量, 自己减少自己的count值, 因此变量不共享。
*/
public static void init() {
new MyThread("A").start();
new MyThread("B").start();
new MyThread("C").start();
}
public static void main(String[] args) {
init();
}
/** 打印结果
* thread B count = 2
* thread C count = 2
* thread C count = 1
* thread C count = 0
* thread B count = 1
* thread B count = 0
* thread A count = 2
* thread A count = 1
* thread A count = 0
*/
}
/** extends Thread 实现变量共享 */
public class MyThread extends Thread {
private static Integer tickets = 5;
private static String str = new String("Sell Tickets");
public MyThread(String threadName) {
super();
this.setName(threadName);
}
@Override
public void run() {
while (true) {
synchronized (str) {
if (tickets > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ " 正在出售第 " + (tickets--) + " 张");
} else {
break;
}
}
}
}
public static void init() {
new MyThread("A").start();
new MyThread("B").start();
new MyThread("C").start();
}
public static void main(String[] args) {
init();
}
/** 打印结果
* thread A tickets = 5
* thread C tickets = 4
* thread B tickets = 3
* thread B tickets = 2
* thread B tickets = 1
*/
}
public class MyThread implements Runnable {
int i = 5;
@Override
public void run() {
while(true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + this.i);
}
}
public static void init() {
MyThread2 target = new MyThread2();
new Thread(target, "A").start();
new Thread(target, "B").start();
new Thread(target, "C").start();
}
public static void main(String[] args) {
init();
}
}
public static void main(String[] args) {
new Thread() {
public void run() {
for (int x = 0; x < 10; x++) {
System.out.println(
Thread.currentThread().getName() + " x = " + x);
}
}
}.start();
}
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
for (int x = 0; x < 10; x++) {
System.out.println(
Thread.currentThread().getName() + " x = " + x);
}
}
}) {
}.start();
}
public static void main(String[] args) {
new Thread(
new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("runnable :"
+ Thread.currentThread().getName());
}
}
}
) {
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(
"thread :" + Thread.currentThread().getName());
}
}
}.start();
}