java线程代码 java线程讲解

java多线程共同操作同一个队列,怎么实现?具体代码如下java线程代码:
以下是两个线程java线程代码:
import java.util.*;
public class Thread_List_Operation {
//假设有这么一个队列
static List list = new LinkedList();
public static void main(String[] args) {
Thread t;
t = new Thread(new T1());
t.start();
t = new Thread(new T2());
t.start();
}
}
//线程T1,用来给list添加新元素
class T1 implements Runnable{
void getElemt(Object o){
Thread_List_Operation.list.add(o);
System.out.println(Thread.currentThread().getName() + "为队列添加java线程代码了一个元素");
}
@Override
public void run() {
for (int i = 0; i10; i++) {
getElemt(new Integer(1));
}
}
}
//线程T2,用来给list添加新元素
class T2 implements Runnable{
void getElemt(Object o){
Thread_List_Operation.list.add(o);
System.out.println(Thread.currentThread().getName() + "为队列添加java线程代码了一个元素");
}
@Override
public void run() {
for (int i = 0; i10; i++) {
getElemt(new Integer(1));
}
}
}
//结果(乱序)
Thread-0为队列添加java线程代码了一个元素
Thread-1为队列添加了一个元素
Thread-0为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-0为队列添加了一个元素
Thread-0为队列添加了一个元素
Thread-0为队列添加了一个元素
Thread-0为队列添加了一个元素
Thread-0为队列添加了一个元素
Thread-0为队列添加了一个元素
Thread-0为队列添加了一个元素
Thread-0为队列添加了一个元素
java线程的经典代码package threadgroup;
class ThreadDemo3 extends Thread {
private String name;
private int delay;
public ThreadDemo3(String sname, int i_delay) {
name = sname;
delay = i_delay;
}
public void run() {
try {
sleep(delay);
} catch (InterruptedException e) {
}
System.out.println("多线程测试java线程代码!\n" + name + "\n" + delay);
}
}
public class testMyThread {
public static void main(String[] args) {
ThreadDemo3 th1,th2,th3;
th1 = new ThreadDemo3("线程1", (int) (Math.random() * 900));
th2 = new ThreadDemo3("线程2", (int) (Math.random() * 900));
th3 = new ThreadDemo3("线程3", (int) (Math.random() * 900));
th1.start();
th2.start();
th3.start();
}
}
package threadgroup;
public class threadDemo {
public static void main(String[] args) {
Thread t = Thread.currentThread();
t.setName("你好吗?");
System.out.println("正在进行java线程代码的Thread是:" + t);
try {
for (int i = 0; i5; i++) {
System.out.println("我不叫穆继超" + i);
Thread.sleep(3000);
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("Thread has wrong" + e.getMessage());
}
}
}
package threadgroup;
public class threadDemo2 implements Runnable {
public threadDemo2() {
Thread t1 = Thread.currentThread();
t1.setName("第一个主进程");
System.out.println("正在运行" + t1);
Thread t2 = new Thread(this, "");
System.out.println("在创建一个进程");
t2.start();
try {

推荐阅读